Compare commits

..

2 Commits

Author SHA1 Message Date
Paddy ec533394ce API-35: First steps in swagger integration 2022-01-08 15:06:39 +01:00
Paddy 5257797866 API-35: First steps in swagger integration 2022-01-08 15:04:49 +01:00
103 changed files with 8212 additions and 16057 deletions
-2
View File
@@ -8,5 +8,3 @@ dist/
logs/
node_modules/
public/
coverage/
testResults/
+7 -49
View File
@@ -2,7 +2,6 @@ import express from 'express';
import * as http from 'http';
import * as dotenv from 'dotenv';
import swaggerUi from 'swagger-ui-express';
import swaggerJSDoc from 'swagger-jsdoc';
// Router imports
import {partyPlanerRouter} from './src/models/partyplaner/PartyPlaner.router';
import {highlightMarkerRouter} from './src/models/twitch-highlight-marker/HighlightMarker.router';
@@ -11,7 +10,6 @@ import logger from './src/middleware/logger';
import {dhbwRaPlaChangesRouter} from './src/models/dhbw-rapla-changes/DHBWRaPlaChanges.router';
import {raPlaMiddlewareRouter} from './src/models/rapla-middleware/RaPlaMiddleware.router';
import {betterzonRouter} from './src/models/betterzon/Betterzon.router';
import {crrRouter} from './src/models/climbing-route-rating/ClimbingRouteRating.router';
let cors = require('cors');
@@ -30,57 +28,18 @@ const server: http.Server = http.createServer(app);
// here we are adding middleware to parse all incoming requests as JSON
app.use(express.json());
// Configure CORS
let allowedHosts = [
'https://rapla.p4ddy.com',
'https://betterzon.p4ddy.com'
];
app.use(cors({
origin: function (origin: any, callback: any) {
// Allow requests with no origin
if (!origin) return callback(null, true);
// Block requests with wrong origin
if (allowedHosts.indexOf(origin) === -1) {
return callback(new Error('The CORS policy doesn\'t allow access for your origin.'), false);
}
// Allow all other requests
return callback(null, true);
}
}));
// Use CORS
app.use(cors());
// Swagger documentation
const swaggerDefinition = {
openapi: '3.0.0',
info: {
title: 'Pluto Development REST API',
version: '2.0.0',
license: {
name: 'Licensed Under MIT',
url: 'https://spdx.org/licenses/MIT.html'
},
contact: {
name: 'Pluto Development',
url: 'https://www.pluto-development.de'
}
}
};
const options = {
swaggerDefinition,
// Paths to files containing OpenAPI definitions
apis: [
'./src/models/**/*.router.ts'
]
};
const swaggerSpec = swaggerJSDoc(options);
app.use(
'/docs',
swaggerUi.serve,
swaggerUi.setup(swaggerSpec)
swaggerUi.setup(undefined, {
swaggerOptions: {
url: '/public/swagger.json'
}
})
);
// Add routers
@@ -90,7 +49,6 @@ app.use('/partyplaner', partyPlanerRouter);
app.use('/raplachanges', dhbwRaPlaChangesRouter);
app.use('/rapla-middleware', raPlaMiddlewareRouter);
app.use('/betterzon', betterzonRouter);
app.use('/crr', crrRouter);
// this is a simple route to make sure everything is working properly
app.get('/', (req: express.Request, res: express.Response) => {
-8
View File
@@ -1,8 +0,0 @@
/** @type {import('ts-jest/dist/types').InitialOptionsTsJest} */
module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
roots: [
'test'
]
};
+1936 -8960
View File
File diff suppressed because it is too large Load Diff
+7 -22
View File
@@ -7,49 +7,34 @@
"start": "tsc && node ./dist/app.js",
"build": "tsc",
"debug": "export DEBUG=* && npm run start",
"test": "jest --coverage --testResultsProcessor ./node_modules/jest-sonar-reporter/index.js"
"test": "echo \"Error: no test specified\" && exit 1",
"swagger": "tsoa spec"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"app-root-path": "^3.0.0",
"axios": "^0.24.0",
"bcrypt": "^5.0.1",
"cors": "^2.8.5",
"debug": "^4.3.1",
"dotenv": "^8.2.0",
"express": "^4.18.2",
"express": "^4.17.1",
"guid-typescript": "^1.0.9",
"mariadb": "^3.0.2",
"random-words": "^1.1.1",
"swagger-jsdoc": "^6.1.0",
"mariadb": "^2.5.3",
"swagger-ui-express": "^4.3.0",
"tsoa": "^3.14.1",
"winston": "^3.3.3"
},
"devDependencies": {
"@types/app-root-path": "^1.2.4",
"@types/bcrypt": "^3.0.1",
"@types/debug": "^4.1.5",
"@types/express": "^4.17.15",
"@types/jest": "^28.1.3",
"@types/node": "^18.11.17",
"@types/random-words": "^1.1.2",
"@types/swagger-jsdoc": "^6.0.1",
"@types/express": "^4.17.11",
"@types/swagger-ui-express": "^4.1.3",
"@types/winston": "^2.4.4",
"is-number": "^7.0.0",
"jest": "^28.1.1",
"jest-sonar-reporter": "^2.0.0",
"source-map-support": "^0.5.19",
"ts-jest": "^28.0.5",
"tslint": "^6.1.3",
"typescript": "^4.9.4"
},
"jestSonar": {
"sonar56x": true,
"reportPath": "testResults",
"reportFile": "sonar-report.xml",
"indent": 4
"typescript": "^4.1.5"
}
}
-6
View File
@@ -1,6 +0,0 @@
sonar.projectKey=pd-api
sonar.sources=src
sonar.tests=test
sonar.language=ts
sonar.javascript.lcov.reportPaths=coverage/lcov.info
sonar.testExecutionReportPaths=testResults/sonar-report.xml
-19
View File
@@ -1,19 +0,0 @@
import * as dotenv from 'dotenv';
const mariadb = require('mariadb');
dotenv.config();
export namespace BetterzonDB {
const pool = mariadb.createPool({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.BETTERZON_DATABASE,
connectionLimit: 5
});
export const getConnection = async () => {
return pool.getConnection();
};
}
+2 -2
View File
@@ -34,8 +34,8 @@ betterzonRouter.use('/crawlingstatus', crawlingstatusRouter);
betterzonRouter.get('/', async (req: Request, res: Response) => {
try {
res.status(200).send('Pluto Development Betterzon API Endpoint');
} catch (e: any) {
res.status(200).send('Pluto Development PartyPlaner API Endpoint V2');
} catch (e) {
let errorGuid = Guid.create().toString();
logger.error('Error handling a request: ' + e.message, {reference: errorGuid});
res.status(500).send({
@@ -25,7 +25,7 @@ categoriesRouter.get('/', async (req: Request, res: Response) => {
const categories: Categories = await CategoryService.findAll();
res.status(200).send(categories);
} catch (e: any) {
} catch (e) {
console.log('Error handling a request: ' + e.message);
res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'}));
}
@@ -44,7 +44,7 @@ categoriesRouter.get('/:id', async (req: Request, res: Response) => {
const category: Category = await CategoryService.find(id);
res.status(200).send(category);
} catch (e: any) {
} catch (e) {
console.log('Error handling a request: ' + e.message);
res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'}));
}
@@ -63,7 +63,7 @@ categoriesRouter.get('/search/:term', async (req: Request, res: Response) => {
const categories: Categories = await CategoryService.findBySearchTerm(term);
res.status(200).send(categories);
} catch (e: any) {
} catch (e) {
console.log('Error handling a request: ' + e.message);
res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'}));
}
@@ -1,10 +1,18 @@
import * as dotenv from 'dotenv';
import {Category} from './category.interface';
import {Categories} from './categories.interface';
import {BetterzonDB} from '../Betterzon.db';
dotenv.config();
const mariadb = require('mariadb');
const pool = mariadb.createPool({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.BETTERZON_DATABASE,
connectionLimit: 5
});
/**
* Data Model Interfaces
*/
@@ -18,9 +26,10 @@ dotenv.config();
* Fetches and returns all known categories
*/
export const findAll = async (): Promise<Categories> => {
let conn = await BetterzonDB.getConnection();
let conn;
let categRows = [];
try {
conn = await pool.getConnection();
const rows = await conn.query('SELECT category_id, name FROM categories');
for (let row in rows) {
if (row !== 'meta') {
@@ -39,8 +48,9 @@ export const findAll = async (): Promise<Categories> => {
} catch (err) {
throw err;
} finally {
// Return connection
await conn.end();
if (conn) {
conn.end();
}
}
return categRows;
@@ -51,9 +61,10 @@ export const findAll = async (): Promise<Categories> => {
* @param id The id of the category to fetch
*/
export const find = async (id: number): Promise<Category> => {
let conn = await BetterzonDB.getConnection();
let conn;
let categ: any;
try {
conn = await pool.getConnection();
const rows = await conn.query('SELECT category_id, name FROM categories WHERE category_id = ?', id);
for (let row in rows) {
if (row !== 'meta') {
@@ -64,8 +75,9 @@ export const find = async (id: number): Promise<Category> => {
} catch (err) {
throw err;
} finally {
// Return connection
await conn.end();
if (conn) {
conn.end();
}
}
return categ;
@@ -76,9 +88,10 @@ export const find = async (id: number): Promise<Category> => {
* @param term the term to match
*/
export const findBySearchTerm = async (term: string): Promise<Categories> => {
let conn = await BetterzonDB.getConnection();
let conn;
let categRows = [];
try {
conn = await pool.getConnection();
term = '%' + term + '%';
const rows = await conn.query('SELECT category_id, name FROM categories WHERE name LIKE ?', term);
for (let row in rows) {
@@ -90,8 +103,9 @@ export const findBySearchTerm = async (term: string): Promise<Categories> => {
} catch (err) {
throw err;
} finally {
// Return connection
await conn.end();
if (conn) {
conn.end();
}
}
return categRows;
@@ -7,6 +7,7 @@ import * as ContactPersonService from './contact_persons.service';
import {Contact_Person} from './contact_person.interface';
import {Contact_Persons} from './contact_persons.interface';
import * as UserService from '../users/users.service';
import * as PriceService from '../prices/prices.service';
/**
@@ -26,7 +27,7 @@ contactpersonsRouter.get('/', async (req: Request, res: Response) => {
const contacts: Contact_Persons = await ContactPersonService.findAll();
res.status(200).send(contacts);
} catch (e: any) {
} catch (e) {
console.log('Error handling a request: ' + e.message);
res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'}));
}
@@ -45,7 +46,7 @@ contactpersonsRouter.get('/:id', async (req: Request, res: Response) => {
const contact: Contact_Person = await ContactPersonService.find(id);
res.status(200).send(contact);
} catch (e: any) {
} catch (e) {
console.log('Error handling a request: ' + e.message);
res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'}));
}
@@ -64,7 +65,7 @@ contactpersonsRouter.get('/byvendor/:id', async (req: Request, res: Response) =>
const contacts: Contact_Persons = await ContactPersonService.findByVendor(id);
res.status(200).send(contacts);
} catch (e: any) {
} catch (e) {
console.log('Error handling a request: ' + e.message);
res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'}));
}
@@ -94,7 +95,7 @@ contactpersonsRouter.post('/', async (req: Request, res: Response) => {
} else {
res.status(500).send({});
}
} catch (e: any) {
} catch (e) {
console.log('Error handling a request: ' + e.message);
res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'}));
}
@@ -125,7 +126,7 @@ contactpersonsRouter.put('/:id', async (req: Request, res: Response) => {
} else {
res.status(500).send({});
}
} catch (e: any) {
} catch (e) {
console.log('Error handling a request: ' + e.message);
res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'}));
}
@@ -1,10 +1,18 @@
import * as dotenv from 'dotenv';
import {Contact_Person} from './contact_person.interface';
import {Contact_Persons} from './contact_persons.interface';
import {BetterzonDB} from '../Betterzon.db';
dotenv.config();
const mariadb = require('mariadb');
const pool = mariadb.createPool({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.BETTERZON_DATABASE,
connectionLimit: 5
});
/**
* Data Model Interfaces
*/
@@ -18,9 +26,10 @@ dotenv.config();
* Fetches and returns all known contact persons
*/
export const findAll = async (): Promise<Contact_Persons> => {
let conn = await BetterzonDB.getConnection();
let conn;
let contRows = [];
try {
conn = await pool.getConnection();
const rows = await conn.query('SELECT contact_person_id, first_name, last_name, gender, email, phone, vendor_id FROM contact_persons');
for (let row in rows) {
if (row !== 'meta') {
@@ -31,8 +40,9 @@ export const findAll = async (): Promise<Contact_Persons> => {
} catch (err) {
throw err;
} finally {
// Return connection
await conn.end();
if (conn) {
conn.end();
}
}
return contRows;
@@ -43,9 +53,10 @@ export const findAll = async (): Promise<Contact_Persons> => {
* @param id The id of the contact person to fetch
*/
export const find = async (id: number): Promise<Contact_Person> => {
let conn = await BetterzonDB.getConnection();
let conn;
let cont: any;
try {
conn = await pool.getConnection();
const rows = await conn.query('SELECT contact_person_id, first_name, last_name, gender, email, phone, vendor_id FROM contact_persons WHERE contact_person_id = ?', id);
for (let row in rows) {
if (row !== 'meta') {
@@ -56,8 +67,9 @@ export const find = async (id: number): Promise<Contact_Person> => {
} catch (err) {
throw err;
} finally {
// Return connection
await conn.end();
if (conn) {
conn.end();
}
}
return cont;
@@ -68,9 +80,10 @@ export const find = async (id: number): Promise<Contact_Person> => {
* @param id The id of the vendor to fetch contact persons for
*/
export const findByVendor = async (id: number): Promise<Contact_Persons> => {
let conn = await BetterzonDB.getConnection();
let conn;
let contRows = [];
try {
conn = await pool.getConnection();
const rows = await conn.query('SELECT contact_person_id, first_name, last_name, gender, email, phone, vendor_id FROM contact_persons WHERE vendor_id = ?', id);
for (let row in rows) {
if (row !== 'meta') {
@@ -81,8 +94,9 @@ export const findByVendor = async (id: number): Promise<Contact_Persons> => {
} catch (err) {
throw err;
} finally {
// Return connection
await conn.end();
if (conn) {
conn.end();
}
}
return contRows;
@@ -99,8 +113,10 @@ export const findByVendor = async (id: number): Promise<Contact_Persons> => {
* @param phone The phone number of the contact person
*/
export const createContactEntry = async (user_id: number, vendor_id: number, first_name: string, last_name: string, gender: string, email: string, phone: string): Promise<Boolean> => {
let conn = await BetterzonDB.getConnection();
let conn;
try {
conn = await pool.getConnection();
// Check if the user is authorized to manage the requested vendor
const user_vendor_rows = await conn.query('SELECT vendor_id FROM vendors WHERE vendor_id = ? AND admin_id = ?', [vendor_id, user_id]);
if (user_vendor_rows.length !== 1) {
@@ -115,8 +131,9 @@ export const createContactEntry = async (user_id: number, vendor_id: number, fir
} catch (err) {
throw err;
} finally {
// Return connection
await conn.end();
if (conn) {
conn.end();
}
}
};
@@ -132,8 +149,10 @@ export const createContactEntry = async (user_id: number, vendor_id: number, fir
* @param phone The phone number of the contact person
*/
export const updateContactEntry = async (user_id: number, contact_person_id: number, vendor_id: number, first_name: string, last_name: string, gender: string, email: string, phone: string): Promise<Boolean> => {
let conn = await BetterzonDB.getConnection();
let conn;
try {
conn = await pool.getConnection();
// Check if the user is authorized to manage the requested vendor
const user_vendor_rows = await conn.query('SELECT vendor_id FROM vendors WHERE vendor_id = ? AND admin_id = ?', [vendor_id, user_id]);
if (user_vendor_rows.length !== 1) {
@@ -148,7 +167,8 @@ export const updateContactEntry = async (user_id: number, contact_person_id: num
} catch (err) {
throw err;
} finally {
// Return connection
await conn.end();
if (conn) {
conn.end();
}
}
};
@@ -5,6 +5,7 @@
import express, {Request, Response} from 'express';
import * as CrawlingStatusService from './crawling_status.service';
import {Crawling_Status} from './crawling_status.interface';
import {Crawling_Statuses} from './crawling_statuses.interface';
import * as UserService from '../users/users.service';
@@ -36,7 +37,7 @@ crawlingstatusRouter.get('/', async (req: Request, res: Response) => {
const status: Crawling_Status = await CrawlingStatusService.getCurrent();
res.status(200).send(status);
} catch (e: any) {
} catch (e) {
console.log('Error handling a request: ' + e.message);
res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'}));
}
@@ -1,9 +1,17 @@
import * as dotenv from 'dotenv';
import {Crawling_Status} from './crawling_status.interface';
import {BetterzonDB} from '../Betterzon.db';
dotenv.config();
const mariadb = require('mariadb');
const pool = mariadb.createPool({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.BETTERZON_DATABASE,
connectionLimit: 5
});
/**
* Data Model Interfaces
*/
@@ -17,8 +25,10 @@ dotenv.config();
* Fetches and returns the current crawling status if the issuing user is an admin
*/
export const getCurrent = async (): Promise<Crawling_Status> => {
let conn = await BetterzonDB.getConnection();
let conn;
try {
conn = await pool.getConnection();
// Get the current crawling process
let process_info = {
process_id: -1,
@@ -56,7 +66,8 @@ export const getCurrent = async (): Promise<Crawling_Status> => {
} catch (err) {
throw err;
} finally {
// Return connection
await conn.end();
if (conn) {
conn.end();
}
}
};
@@ -4,6 +4,8 @@
import express, {Request, Response} from 'express';
import * as FavoriteShopsService from './favoriteshops.service';
import {FavoriteShop} from './favoriteshop.interface';
import {FavoriteShops} from './favoriteshops.interface';
import * as UserService from '../users/users.service';
@@ -29,7 +31,7 @@ favoriteshopsRouter.get('/', async (req: Request, res: Response) => {
const priceAlarms = await FavoriteShopsService.getFavoriteShops(user.user_id);
res.status(200).send(priceAlarms);
} catch (e: any) {
} catch (e) {
console.log('Error handling a request: ' + e.message);
res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'}));
}
@@ -63,7 +65,7 @@ favoriteshopsRouter.post('/', async (req: Request, res: Response) => {
res.status(500).send(JSON.stringify({success: false}));
return;
}
} catch (e: any) {
} catch (e) {
console.log('Error handling a request: ' + e.message);
res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'}));
}
@@ -97,7 +99,7 @@ favoriteshopsRouter.delete('/:id', async (req: Request, res: Response) => {
res.status(500).send(JSON.stringify({success: false}));
return;
}
} catch (e: any) {
} catch (e) {
console.log('Error handling a request: ' + e.message);
res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'}));
}
@@ -1,9 +1,17 @@
import * as dotenv from 'dotenv';
import {FavoriteShops} from './favoriteshops.interface';
import {BetterzonDB} from '../Betterzon.db';
dotenv.config();
const mariadb = require('mariadb');
const pool = mariadb.createPool({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.BETTERZON_DATABASE,
connectionLimit: 5
});
/**
* Data Model Interfaces
*/
@@ -19,16 +27,18 @@ dotenv.config();
* @param vendor_id The id of the vendor to set as favorite
*/
export const createFavoriteShop = async (user_id: number, vendor_id: number): Promise<boolean> => {
let conn = await BetterzonDB.getConnection();
let conn;
try {
conn = await pool.getConnection();
const res = await conn.query('INSERT INTO favorite_shops (vendor_id, user_id) VALUES (?, ?)', [vendor_id, user_id]);
return res.affectedRows === 1;
} catch (err) {
throw err;
} finally {
// Return connection
await conn.end();
if (conn) {
conn.end();
}
}
};
@@ -37,9 +47,10 @@ export const createFavoriteShop = async (user_id: number, vendor_id: number): Pr
* @param user_id
*/
export const getFavoriteShops = async (user_id: number): Promise<FavoriteShops> => {
let conn = await BetterzonDB.getConnection();
let conn;
let shops = [];
try {
conn = await pool.getConnection();
const rows = await conn.query('SELECT favorite_id, vendor_id, user_id FROM favorite_shops WHERE user_id = ?', user_id);
for (let row in rows) {
if (row !== 'meta') {
@@ -51,8 +62,9 @@ export const getFavoriteShops = async (user_id: number): Promise<FavoriteShops>
} catch (err) {
throw err;
} finally {
// Return connection
await conn.end();
if (conn) {
conn.end();
}
}
};
@@ -62,15 +74,17 @@ export const getFavoriteShops = async (user_id: number): Promise<FavoriteShops>
* @param favorite_id The favorite shop to delete
*/
export const deleteFavoriteShop = async (user_id: number, favorite_id: number): Promise<boolean> => {
let conn = await BetterzonDB.getConnection();
let conn;
try {
conn = await pool.getConnection();
const res = await conn.query('DELETE FROM favorite_shops WHERE favorite_id = ? AND user_id = ?', [favorite_id, user_id]);
return res.affectedRows === 1;
} catch (err) {
throw err;
} finally {
// Return connection
await conn.end();
if (conn) {
conn.end();
}
}
};
@@ -25,7 +25,7 @@ manufacturersRouter.get('/', async (req: Request, res: Response) => {
const manufacturers: Manufacturers = await ManufacturerService.findAll();
res.status(200).send(manufacturers);
} catch (e: any) {
} catch (e) {
console.log('Error handling a request: ' + e.message);
res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'}));
}
@@ -44,7 +44,7 @@ manufacturersRouter.get('/:id', async (req: Request, res: Response) => {
const manufacturer: Manufacturer = await ManufacturerService.find(id);
res.status(200).send(manufacturer);
} catch (e: any) {
} catch (e) {
console.log('Error handling a request: ' + e.message);
res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'}));
}
@@ -63,7 +63,7 @@ manufacturersRouter.get('/search/:term', async (req: Request, res: Response) =>
const manufacturer: Manufacturers = await ManufacturerService.findBySearchTerm(term);
res.status(200).send(manufacturer);
} catch (e: any) {
} catch (e) {
console.log('Error handling a request: ' + e.message);
res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'}));
}
@@ -1,10 +1,18 @@
import * as dotenv from 'dotenv';
import {Manufacturer} from './manufacturer.interface';
import {Manufacturers} from './manufacturers.interface';
import {BetterzonDB} from '../Betterzon.db';
dotenv.config();
const mariadb = require('mariadb');
const pool = mariadb.createPool({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.BETTERZON_DATABASE,
connectionLimit: 5
});
/**
* Data Model Interfaces
*/
@@ -18,9 +26,10 @@ dotenv.config();
* Fetches and returns all known manufacturers
*/
export const findAll = async (): Promise<Manufacturers> => {
let conn = await BetterzonDB.getConnection();
let conn;
let manRows = [];
try {
conn = await pool.getConnection();
const rows = await conn.query('SELECT manufacturer_id, name FROM manufacturers');
for (let row in rows) {
if (row !== 'meta') {
@@ -39,8 +48,9 @@ export const findAll = async (): Promise<Manufacturers> => {
} catch (err) {
throw err;
} finally {
// Return connection
await conn.end();
if (conn) {
conn.end();
}
}
return manRows;
@@ -51,9 +61,10 @@ export const findAll = async (): Promise<Manufacturers> => {
* @param id The id of the manufacturer to fetch
*/
export const find = async (id: number): Promise<Manufacturer> => {
let conn = await BetterzonDB.getConnection();
let conn;
let man: any;
try {
conn = await pool.getConnection();
const rows = await conn.query('SELECT manufacturer_id, name FROM manufacturers WHERE manufacturer_id = ?', id);
for (let row in rows) {
if (row !== 'meta') {
@@ -64,8 +75,9 @@ export const find = async (id: number): Promise<Manufacturer> => {
} catch (err) {
throw err;
} finally {
// Return connection
await conn.end();
if (conn) {
conn.end();
}
}
return man;
@@ -76,9 +88,10 @@ export const find = async (id: number): Promise<Manufacturer> => {
* @param term the term to match
*/
export const findBySearchTerm = async (term: string): Promise<Manufacturers> => {
let conn = await BetterzonDB.getConnection();
let conn;
let manRows = [];
try {
conn = await pool.getConnection();
term = '%' + term + '%';
const rows = await conn.query('SELECT manufacturer_id, name FROM manufacturers WHERE name LIKE ?', term);
for (let row in rows) {
@@ -90,8 +103,9 @@ export const findBySearchTerm = async (term: string): Promise<Manufacturers> =>
} catch (err) {
throw err;
} finally {
// Return connection
await conn.end();
if (conn) {
conn.end();
}
}
return manRows;
@@ -4,6 +4,8 @@
import express, {Request, Response} from 'express';
import * as PriceAlarmsService from './pricealarms.service';
import {PriceAlarm} from './pricealarm.interface';
import {PriceAlarms} from './pricealarms.interface';
import * as UserService from '../users/users.service';
@@ -29,7 +31,7 @@ pricealarmsRouter.get('/', async (req: Request, res: Response) => {
const priceAlarms = await PriceAlarmsService.getPriceAlarms(user.user_id);
res.status(200).send(priceAlarms);
} catch (e: any) {
} catch (e) {
console.log('Error handling a request: ' + e.message);
res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'}));
}
@@ -64,7 +66,7 @@ pricealarmsRouter.post('/', async (req: Request, res: Response) => {
res.status(500).send(JSON.stringify({success: false}));
return;
}
} catch (e: any) {
} catch (e) {
console.log('Error handling a request: ' + e.message);
res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'}));
}
@@ -99,7 +101,7 @@ pricealarmsRouter.put('/', async (req: Request, res: Response) => {
res.status(500).send(JSON.stringify({success: false}));
return;
}
} catch (e: any) {
} catch (e) {
console.log('Error handling a request: ' + e.message);
res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'}));
}
@@ -125,7 +127,7 @@ pricealarmsRouter.delete('/:id', async (req, res) => {
res.status(500).send(JSON.stringify({success: false}));
return;
}
} catch (e: any) {
} catch (e) {
console.log('Error handling a request: ' + e.message);
res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'}));
}
@@ -1,9 +1,17 @@
import * as dotenv from 'dotenv';
import {PriceAlarms} from './pricealarms.interface';
import {BetterzonDB} from '../Betterzon.db';
dotenv.config();
const mariadb = require('mariadb');
const pool = mariadb.createPool({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.BETTERZON_DATABASE,
connectionLimit: 5
});
/**
* Data Model Interfaces
*/
@@ -20,16 +28,18 @@ dotenv.config();
* @param defined_price The defined price for the price alarm
*/
export const createPriceAlarm = async (user_id: number, product_id: number, defined_price: number): Promise<boolean> => {
let conn = await BetterzonDB.getConnection();
let conn;
try {
conn = await pool.getConnection();
const res = await conn.query('INSERT INTO price_alarms (user_id, product_id, defined_price) VALUES (?, ?, ?)', [user_id, product_id, defined_price]);
return res.affectedRows === 1;
} catch (err) {
throw err;
} finally {
// Return connection
await conn.end();
if (conn) {
conn.end();
}
}
};
@@ -38,9 +48,10 @@ export const createPriceAlarm = async (user_id: number, product_id: number, defi
* @param user_id
*/
export const getPriceAlarms = async (user_id: number): Promise<PriceAlarms> => {
let conn = await BetterzonDB.getConnection();
let conn;
let priceAlarms = [];
try {
conn = await pool.getConnection();
const rows = await conn.query('SELECT alarm_id, user_id, product_id, defined_price FROM price_alarms WHERE user_id = ?', user_id);
for (let row in rows) {
if (row !== 'meta') {
@@ -52,8 +63,9 @@ export const getPriceAlarms = async (user_id: number): Promise<PriceAlarms> => {
} catch (err) {
throw err;
} finally {
// Return connection
await conn.end();
if (conn) {
conn.end();
}
}
};
@@ -64,16 +76,18 @@ export const getPriceAlarms = async (user_id: number): Promise<PriceAlarms> => {
* @param defined_price The defined price for the price alarm
*/
export const updatePriceAlarm = async (alarm_id: number, user_id: number, defined_price: number): Promise<boolean> => {
let conn = await BetterzonDB.getConnection();
let conn;
try {
conn = await pool.getConnection();
const res = await conn.query('UPDATE price_alarms SET defined_price = ? WHERE alarm_id = ? AND user_id = ?', [defined_price, alarm_id, user_id]);
return res.affectedRows === 1;
} catch (err) {
throw err;
} finally {
// Return connection
await conn.end();
if (conn) {
conn.end();
}
}
};
@@ -83,15 +97,17 @@ export const updatePriceAlarm = async (alarm_id: number, user_id: number, define
* @param user_id The id of the user that wants to update the price alarm
*/
export const deletePriceAlarm = async (alarm_id: number, user_id: number): Promise<boolean> => {
let conn = await BetterzonDB.getConnection();
let conn;
try {
conn = await pool.getConnection();
const res = await conn.query('DELETE FROM price_alarms WHERE alarm_id = ? AND user_id = ?', [alarm_id, user_id]);
return res.affectedRows === 1;
} catch (err) {
throw err;
} finally {
// Return connection
await conn.end();
if (conn) {
conn.end();
}
}
};
+7 -7
View File
@@ -30,16 +30,16 @@ pricesRouter.get('/', async (req: Request, res: Response) => {
if (product) {
if (vendor) {
prices = await PriceService.findByVendor(<string>product, <string>vendor, <string>type);
prices = await PriceService.findByVendor(<string> product, <string> vendor, <string> type);
} else {
prices = await PriceService.findByType(<string>product, <string>type);
prices = await PriceService.findByType(<string> product, <string> type);
}
} else {
prices = await PriceService.findAll();
}
res.status(200).send(prices);
} catch (e: any) {
} catch (e) {
console.log('Error handling a request: ' + e.message);
res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'}));
}
@@ -58,7 +58,7 @@ pricesRouter.get('/:id', async (req: Request, res: Response) => {
const price: Price = await PriceService.find(id);
res.status(200).send(price);
} catch (e: any) {
} catch (e) {
console.log('Error handling a request: ' + e.message);
res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'}));
}
@@ -77,7 +77,7 @@ pricesRouter.get('/bestDeals/:amount', async (req: Request, res: Response) => {
const prices: Prices = await PriceService.getBestDeals(amount);
res.status(200).send(prices);
} catch (e: any) {
} catch (e) {
console.log('Error handling a request: ' + e.message);
res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'}));
}
@@ -96,7 +96,7 @@ pricesRouter.get('/byProduct/list/:ids', async (req: Request, res: Response) =>
const prices: Prices = await PriceService.findListByProducts(productIds);
res.status(200).send(prices);
} catch (e: any) {
} catch (e) {
console.log('Error handling a request: ' + e.message);
res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'}));
}
@@ -123,7 +123,7 @@ pricesRouter.post('/', async (req: Request, res: Response) => {
} else {
res.status(500).send({});
}
} catch (e: any) {
} catch (e) {
console.log('Error handling a request: ' + e.message);
res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'}));
}
+52 -25
View File
@@ -1,10 +1,18 @@
import * as dotenv from 'dotenv';
import {Deal, Price} from './price.interface';
import {Prices} from './prices.interface';
import {BetterzonDB} from '../Betterzon.db';
dotenv.config();
const mariadb = require('mariadb');
const pool = mariadb.createPool({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.BETTERZON_DATABASE,
connectionLimit: 5
});
/**
* Data Model Interfaces
*/
@@ -18,9 +26,10 @@ dotenv.config();
* Fetches and returns all known prices
*/
export const findAll = async (): Promise<Prices> => {
let conn = await BetterzonDB.getConnection();
let conn;
let priceRows = [];
try {
conn = await pool.getConnection();
const rows = await conn.query('SELECT price_id, product_id, v.vendor_id, price_in_cents, timestamp FROM prices p LEFT OUTER JOIN vendors v ON v.vendor_id = p.vendor_id WHERE active_listing = true AND v.isActive = true');
for (let row in rows) {
if (row !== 'meta') {
@@ -45,8 +54,9 @@ export const findAll = async (): Promise<Prices> => {
} catch (err) {
throw err;
} finally {
// Return connection
await conn.end();
if (conn) {
conn.end();
}
}
return priceRows;
@@ -57,9 +67,10 @@ export const findAll = async (): Promise<Prices> => {
* @param id The id of the price to fetch
*/
export const find = async (id: number): Promise<Price> => {
let conn = await BetterzonDB.getConnection();
let conn;
let price: any;
try {
conn = await pool.getConnection();
const rows = await conn.query('SELECT price_id, product_id, p.vendor_id, price_in_cents, timestamp FROM prices p LEFT OUTER JOIN vendors v ON v.vendor_id = p.vendor_id WHERE price_id = ? AND active_listing = true AND v.isActive = true', id);
for (let row in rows) {
if (row !== 'meta') {
@@ -70,8 +81,9 @@ export const find = async (id: number): Promise<Price> => {
} catch (err) {
throw err;
} finally {
// Return connection
await conn.end();
if (conn) {
conn.end();
}
}
return price;
@@ -82,9 +94,10 @@ export const find = async (id: number): Promise<Price> => {
* @param product the product to fetch the prices for
*/
export const findByProduct = async (product: number): Promise<Prices> => {
let conn = await BetterzonDB.getConnection();
let conn;
let priceRows = [];
try {
conn = await pool.getConnection();
const rows = await conn.query('SELECT price_id, product_id, p.vendor_id, price_in_cents, timestamp FROM prices p LEFT OUTER JOIN vendors v ON v.vendor_id = p.vendor_id WHERE product_id = ? AND active_listing = true AND v.isActive = true', product);
for (let row in rows) {
if (row !== 'meta') {
@@ -95,8 +108,9 @@ export const findByProduct = async (product: number): Promise<Prices> => {
} catch (err) {
throw err;
} finally {
// Return connection
await conn.end();
if (conn) {
conn.end();
}
}
return priceRows;
@@ -111,9 +125,10 @@ export const findByProduct = async (product: number): Promise<Prices> => {
* @param type The type of prices, e.g. newest / lowest
*/
export const findByType = async (product: string, type: string): Promise<Prices> => {
let conn = await BetterzonDB.getConnection();
let conn;
let priceRows = [];
try {
conn = await pool.getConnection();
let rows = [];
if (type === 'newest') {
// Used to get the newest price for this product per vendor
@@ -148,8 +163,9 @@ export const findByType = async (product: string, type: string): Promise<Prices>
} catch (err) {
throw err;
} finally {
// Return connection
await conn.end();
if (conn) {
conn.end();
}
}
return priceRows;
@@ -165,9 +181,10 @@ export const findByType = async (product: string, type: string): Promise<Prices>
* @param type The type of prices, e.g. newest / lowest
*/
export const findByVendor = async (product: string, vendor: string, type: string): Promise<Prices> => {
let conn = await BetterzonDB.getConnection();
let conn;
let priceRows = [];
try {
conn = await pool.getConnection();
let rows = [];
if (type === 'newest') {
// Used to get the newest price for this product and vendor
@@ -189,8 +206,9 @@ export const findByVendor = async (product: string, vendor: string, type: string
} catch (err) {
throw err;
} finally {
// Return connection
await conn.end();
if (conn) {
conn.end();
}
}
return priceRows;
@@ -202,9 +220,11 @@ export const findByVendor = async (product: string, vendor: string, type: string
* @param amount The amount of deals to return
*/
export const getBestDeals = async (amount: number): Promise<Prices> => {
let conn = await BetterzonDB.getConnection();
let conn;
let priceRows = [];
try {
conn = await pool.getConnection();
let allPrices: Record<number, Price[]> = {};
// Get newest prices for every product at every vendor
@@ -284,8 +304,9 @@ export const getBestDeals = async (amount: number): Promise<Prices> => {
console.log(err);
throw err;
} finally {
// Return connection
await conn.end();
if (conn) {
conn.end();
}
}
return priceRows;
@@ -296,9 +317,11 @@ export const getBestDeals = async (amount: number): Promise<Prices> => {
* @param productIds the ids of the products
*/
export const findListByProducts = async (productIds: [number]): Promise<Prices> => {
let conn = await BetterzonDB.getConnection();
let conn;
let priceRows: Price[] = [];
try {
conn = await pool.getConnection();
let allPrices: Record<number, Price[]> = {};
// Get newest prices for every given product at every vendor
@@ -344,16 +367,19 @@ export const findListByProducts = async (productIds: [number]): Promise<Prices>
} catch (err) {
throw err;
} finally {
// Return connection
await conn.end();
if (conn) {
conn.end();
}
}
return priceRows;
};
export const createPriceEntry = async (user_id: number, vendor_id: number, product_id: number, price_in_cents: number): Promise<Boolean> => {
let conn = await BetterzonDB.getConnection();
let conn;
try {
conn = await pool.getConnection();
// Check if the user is authorized to manage the requested vendor
const user_vendor_rows = await conn.query('SELECT vendor_id FROM vendors WHERE vendor_id = ? AND admin_id = ?', [vendor_id, user_id]);
if (user_vendor_rows.length !== 1) {
@@ -368,7 +394,8 @@ export const createPriceEntry = async (user_id: number, vendor_id: number, produ
} catch (err) {
throw err;
} finally {
// Return connection
await conn.end();
if (conn) {
conn.end();
}
}
};
@@ -25,7 +25,7 @@ productsRouter.get('/', async (req: Request, res: Response) => {
const products: Products = await ProductService.findAll();
res.status(200).send(products);
} catch (e: any) {
} catch (e) {
console.log('Error handling a request: ' + e.message);
res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'}));
}
@@ -44,7 +44,7 @@ productsRouter.get('/:id', async (req: Request, res: Response) => {
const product: Product = await ProductService.find(id);
res.status(200).send(product);
} catch (e: any) {
} catch (e) {
console.log('Error handling a request: ' + e.message);
res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'}));
}
@@ -63,7 +63,7 @@ productsRouter.get('/search/:term', async (req: Request, res: Response) => {
const products: Products = await ProductService.findBySearchTerm(term);
res.status(200).send(products);
} catch (e: any) {
} catch (e) {
console.log('Error handling a request: ' + e.message);
res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'}));
}
@@ -82,7 +82,7 @@ productsRouter.get('/list/:ids', async (req: Request, res: Response) => {
const products: Products = await ProductService.findList(ids);
res.status(200).send(products);
} catch (e: any) {
} catch (e) {
console.log('Error handling a request: ' + e.message);
res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'}));
}
@@ -101,7 +101,7 @@ productsRouter.get('/vendor/:id', async (req: Request, res: Response) => {
const products: Products = await ProductService.findByVendor(id);
res.status(200).send(products);
} catch (e: any) {
} catch (e) {
console.log('Error handling a request: ' + e.message);
res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'}));
}
@@ -124,7 +124,7 @@ productsRouter.post('/', async (req: Request, res: Response) => {
} else {
res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'}));
}
} catch (e: any) {
} catch (e) {
console.log('Error handling a request: ' + e.message);
res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'}));
}
@@ -2,10 +2,18 @@ import * as dotenv from 'dotenv';
import {Product} from './product.interface';
import {Products} from './products.interface';
import * as http from 'http';
import {BetterzonDB} from '../Betterzon.db';
dotenv.config();
const mariadb = require('mariadb');
const pool = mariadb.createPool({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.BETTERZON_DATABASE,
connectionLimit: 5
});
/**
* Data Model Interfaces
*/
@@ -19,9 +27,10 @@ dotenv.config();
* Fetches and returns all known products
*/
export const findAll = async (): Promise<Products> => {
let conn = await BetterzonDB.getConnection();
let conn;
let prodRows = [];
try {
conn = await pool.getConnection();
const rows = await conn.query('SELECT product_id, name, asin, is_active, short_description, long_description, image_guid, date_added, last_modified, manufacturer_id, selling_rank, category_id FROM products');
for (let row in rows) {
if (row !== 'meta') {
@@ -60,8 +69,9 @@ export const findAll = async (): Promise<Products> => {
} catch (err) {
throw err;
} finally {
// Return connection
await conn.end();
if (conn) {
conn.end();
}
}
return prodRows;
@@ -72,9 +82,10 @@ export const findAll = async (): Promise<Products> => {
* @param id The id of the product to fetch
*/
export const find = async (id: number): Promise<Product> => {
let conn = await BetterzonDB.getConnection();
let conn;
let prod: any;
try {
conn = await pool.getConnection();
const rows = await conn.query('SELECT product_id, name, asin, is_active, short_description, long_description, image_guid, date_added, last_modified, manufacturer_id, selling_rank, category_id FROM products WHERE product_id = ?', id);
for (let row in rows) {
if (row !== 'meta') {
@@ -85,8 +96,9 @@ export const find = async (id: number): Promise<Product> => {
} catch (err) {
throw err;
} finally {
// Return connection
await conn.end();
if (conn) {
conn.end();
}
}
return prod;
@@ -97,9 +109,10 @@ export const find = async (id: number): Promise<Product> => {
* @param term the term to match
*/
export const findBySearchTerm = async (term: string): Promise<Products> => {
let conn = await BetterzonDB.getConnection();
let conn;
let prodRows = [];
try {
conn = await pool.getConnection();
term = '%' + term + '%';
const rows = await conn.query('SELECT product_id, name, asin, is_active, short_description, long_description, image_guid, date_added, last_modified, manufacturer_id, selling_rank, category_id FROM products WHERE name LIKE ?', term);
for (let row in rows) {
@@ -112,8 +125,9 @@ export const findBySearchTerm = async (term: string): Promise<Products> => {
console.log(err);
throw err;
} finally {
// Return connection
await conn.end();
if (conn) {
conn.end();
}
}
return prodRows;
@@ -124,9 +138,10 @@ export const findBySearchTerm = async (term: string): Promise<Products> => {
* @param ids The list of product ids to fetch the details for
*/
export const findList = async (ids: [number]): Promise<Products> => {
let conn = await BetterzonDB.getConnection();
let conn;
let prodRows = [];
try {
conn = await pool.getConnection();
const rows = await conn.query('SELECT product_id, name, asin, is_active, short_description, long_description, image_guid, date_added, last_modified, manufacturer_id, selling_rank, category_id FROM products WHERE product_id IN (?)', [ids]);
for (let row in rows) {
if (row !== 'meta') {
@@ -137,8 +152,9 @@ export const findList = async (ids: [number]): Promise<Products> => {
} catch (err) {
throw err;
} finally {
// Return connection
await conn.end();
if (conn) {
conn.end();
}
}
return prodRows;
@@ -149,9 +165,11 @@ export const findList = async (ids: [number]): Promise<Products> => {
* @param id The id of the vendor to fetch the products for
*/
export const findByVendor = async (id: number): Promise<Products> => {
let conn = await BetterzonDB.getConnection();
let conn;
let prodRows = [];
try {
conn = await pool.getConnection();
// Get the relevant product ids
let relevant_prod_ids = [];
const relevantProds = await conn.query('SELECT product_id FROM prices WHERE vendor_id = ? GROUP BY product_id', id);
@@ -172,8 +190,9 @@ export const findByVendor = async (id: number): Promise<Products> => {
} catch (err) {
throw err;
} finally {
// Return connection
await conn.end();
if (conn) {
conn.end();
}
}
return prodRows;
+5 -4
View File
@@ -5,6 +5,7 @@
import express, {Request, Response} from 'express';
import * as UserService from './users.service';
import {User} from './user.interface';
import {Users} from './users.interface';
import {Session} from './session.interface';
@@ -50,7 +51,7 @@ usersRouter.post('/register', async (req: Request, res: Response) => {
session_id: session.session_id,
session_key: session.session_key
});
} catch (e: any) {
} catch (e) {
console.log('Error handling a request: ' + e.message);
res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'}));
}
@@ -83,7 +84,7 @@ usersRouter.post('/login', async (req: Request, res: Response) => {
session_id: session.session_id,
session_key: session.session_key
});
} catch (e: any) {
} catch (e) {
console.log('Error handling a request: ' + e.message);
res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'}));
}
@@ -96,7 +97,7 @@ usersRouter.post('/checkSessionValid', async (req: Request, res: Response) => {
const session_id = req.body.session_id;
const session_key = req.body.session_key;
if (!session_id || !session_key) {
if(!session_id || !session_key) {
// Error logging in, probably wrong username / password
res.status(401).send(JSON.stringify({messages: ['No session detected'], codes: [5]}));
return;
@@ -113,7 +114,7 @@ usersRouter.post('/checkSessionValid', async (req: Request, res: Response) => {
// Send the session details back to the user
res.status(200).send(user);
} catch (e: any) {
} catch (e) {
console.log('Error handling a request: ' + e.message);
res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'}));
}
+33 -13
View File
@@ -3,11 +3,19 @@ import * as bcrypt from 'bcrypt';
import {Guid} from 'guid-typescript';
import {User} from './user.interface';
import {Session} from './session.interface';
import {BetterzonDB} from '../Betterzon.db';
dotenv.config();
const mariadb = require('mariadb');
const pool = mariadb.createPool({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.BETTERZON_DATABASE,
connectionLimit: 5
});
/**
* Data Model Interfaces
*/
@@ -21,7 +29,7 @@ dotenv.config();
* Creates a user record in the database, also creates a session. Returns the session if successful.
*/
export const createUser = async (username: string, password: string, email: string, ip: string): Promise<Session> => {
let conn = await BetterzonDB.getConnection();
let conn;
try {
// Hash password and generate + hash session key
const pwHash = bcrypt.hashSync(password, 10);
@@ -29,6 +37,7 @@ export const createUser = async (username: string, password: string, email: stri
const sessionKeyHash = bcrypt.hashSync(sessionKey, 10);
// Create user entry in SQL
conn = await pool.getConnection();
const userQuery = 'INSERT INTO users (username, email, bcrypt_password_hash) VALUES (?, ?, ?) RETURNING user_id';
const userIdRes = await conn.query(userQuery, [username, email, pwHash]);
await conn.commit();
@@ -64,9 +73,12 @@ export const createUser = async (username: string, password: string, email: stri
} catch (err) {
throw err;
} finally {
// Return connection
await conn.end();
if (conn) {
conn.end();
}
}
return {} as Session;
};
/**
@@ -74,9 +86,10 @@ export const createUser = async (username: string, password: string, email: stri
* Returns the session information in case of a successful login
*/
export const login = async (username: string, password: string, ip: string): Promise<Session> => {
let conn = await BetterzonDB.getConnection();
let conn;
try {
// Get saved password hash
conn = await pool.getConnection();
const query = 'SELECT user_id, bcrypt_password_hash FROM users WHERE username = ?';
const userRows = await conn.query(query, username);
let savedHash = '';
@@ -127,18 +140,22 @@ export const login = async (username: string, password: string, ip: string): Pro
} catch (err) {
throw err;
} finally {
// Return connection
await conn.end();
if (conn) {
conn.end();
}
}
return {} as Session;
};
/**
* Checks if the given session information are valid and returns the user information if they are
*/
export const checkSession = async (sessionId: string, sessionKey: string, ip: string): Promise<User> => {
let conn = await BetterzonDB.getConnection();
let conn;
try {
// Get saved session key hash
conn = await pool.getConnection();
const query = 'SELECT user_id, session_key_hash, validUntil FROM sessions WHERE session_id = ?';
const sessionRows = await conn.query(query, sessionId);
let savedHash = '';
@@ -205,8 +222,9 @@ export const checkSession = async (sessionId: string, sessionKey: string, ip: st
} catch (err) {
throw err;
} finally {
// Return connection
await conn.end();
if (conn) {
conn.end();
}
}
};
@@ -239,9 +257,10 @@ export interface Status {
* @param email The email to check
*/
export const checkUsernameAndEmail = async (username: string, email: string): Promise<Status> => {
let conn = await BetterzonDB.getConnection();
let conn;
try {
// Create user entry in SQL
conn = await pool.getConnection();
const usernameQuery = 'SELECT username FROM users WHERE username = ?';
const emailQuery = 'SELECT email FROM users WHERE email = ?';
const usernameRes = await conn.query(usernameQuery, username);
@@ -288,7 +307,8 @@ export const checkUsernameAndEmail = async (username: string, email: string): Pr
} catch (err) {
throw err;
} finally {
// Return connection
await conn.end();
if (conn) {
conn.end();
}
}
};
+7 -7
View File
@@ -26,7 +26,7 @@ vendorsRouter.get('/', async (req: Request, res: Response) => {
const vendors: Vendors = await VendorService.findAll();
res.status(200).send(vendors);
} catch (e: any) {
} catch (e) {
console.log('Error handling a request: ' + e.message);
res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'}));
}
@@ -44,7 +44,7 @@ vendorsRouter.get('/managed', async (req: Request, res: Response) => {
const vendors = await VendorService.getManagedShops(user.user_id);
res.status(200).send(vendors);
} catch (e: any) {
} catch (e) {
console.log('Error handling a request: ' + e.message);
res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'}));
}
@@ -63,7 +63,7 @@ vendorsRouter.get('/:id', async (req: Request, res: Response) => {
const vendor: Vendor = await VendorService.find(id);
res.status(200).send(vendor);
} catch (e: any) {
} catch (e) {
console.log('Error handling a request: ' + e.message);
res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'}));
}
@@ -82,7 +82,7 @@ vendorsRouter.get('/search/:term', async (req: Request, res: Response) => {
const vendors: Vendors = await VendorService.findBySearchTerm(term);
res.status(200).send(vendors);
} catch (e: any) {
} catch (e) {
console.log('Error handling a request: ' + e.message);
res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'}));
}
@@ -108,7 +108,7 @@ vendorsRouter.put('/manage/deactivatelisting', async (req: Request, res: Respons
} else {
res.status(500).send({});
}
} catch (e: any) {
} catch (e) {
console.log('Error handling a request: ' + e.message);
res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'}));
}
@@ -133,7 +133,7 @@ vendorsRouter.put('/manage/shop/deactivate/:id', async (req: Request, res: Respo
} else {
res.status(500).send({});
}
} catch (e: any) {
} catch (e) {
console.log('Error handling a request: ' + e.message);
res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'}));
}
@@ -158,7 +158,7 @@ vendorsRouter.put('/manage/shop/activate/:id', async (req: Request, res: Respons
} else {
res.status(500).send({});
}
} catch (e: any) {
} catch (e) {
console.log('Error handling a request: ' + e.message);
res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'}));
}
+45 -19
View File
@@ -1,10 +1,18 @@
import * as dotenv from 'dotenv';
import {Vendor} from './vendor.interface';
import {Vendors} from './vendors.interface';
import {BetterzonDB} from '../Betterzon.db';
dotenv.config();
const mariadb = require('mariadb');
const pool = mariadb.createPool({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.BETTERZON_DATABASE,
connectionLimit: 5
});
/**
* Data Model Interfaces
*/
@@ -18,9 +26,10 @@ dotenv.config();
* Fetches and returns all known vendors
*/
export const findAll = async (): Promise<Vendors> => {
let conn = await BetterzonDB.getConnection();
let conn;
let vendorRows = [];
try {
conn = await pool.getConnection();
const rows = await conn.query('SELECT vendor_id, name, streetname, zip_code, city, country_code, phone, website FROM vendors WHERE isActive = true');
for (let row in rows) {
if (row !== 'meta') {
@@ -51,8 +60,9 @@ export const findAll = async (): Promise<Vendors> => {
} catch (err) {
throw err;
} finally {
// Return connection
await conn.end();
if (conn) {
conn.end();
}
}
return vendorRows;
@@ -63,9 +73,10 @@ export const findAll = async (): Promise<Vendors> => {
* @param id The id of the vendor to fetch
*/
export const find = async (id: number): Promise<Vendor> => {
let conn = await BetterzonDB.getConnection();
let conn;
let vendor: any;
try {
conn = await pool.getConnection();
const rows = await conn.query('SELECT vendor_id, name, streetname, zip_code, city, country_code, phone, website FROM vendors WHERE vendor_id = ? AND isActive = true', id);
for (let row in rows) {
if (row !== 'meta') {
@@ -76,8 +87,9 @@ export const find = async (id: number): Promise<Vendor> => {
} catch (err) {
throw err;
} finally {
// Return connection
await conn.end();
if (conn) {
conn.end();
}
}
return vendor;
@@ -88,9 +100,10 @@ export const find = async (id: number): Promise<Vendor> => {
* @param term the term to match
*/
export const findBySearchTerm = async (term: string): Promise<Vendors> => {
let conn = await BetterzonDB.getConnection();
let conn;
let vendorRows = [];
try {
conn = await pool.getConnection();
term = '%' + term + '%';
const rows = await conn.query('SELECT vendor_id, name, streetname, zip_code, city, country_code, phone, website FROM vendors WHERE name LIKE ? AND isActive = true', term);
for (let row in rows) {
@@ -102,8 +115,9 @@ export const findBySearchTerm = async (term: string): Promise<Vendors> => {
} catch (err) {
throw err;
} finally {
// Return connection
await conn.end();
if (conn) {
conn.end();
}
}
return vendorRows;
@@ -114,9 +128,10 @@ export const findBySearchTerm = async (term: string): Promise<Vendors> => {
* @param user The user to return the managed shops for
*/
export const getManagedShops = async (user_id: number): Promise<Vendors> => {
let conn = await BetterzonDB.getConnection();
let conn;
let vendorRows = [];
try {
conn = await pool.getConnection();
const rows = await conn.query('SELECT vendor_id, name, streetname, zip_code, city, country_code, phone, website FROM vendors WHERE admin_id LIKE ?', user_id);
for (let row in rows) {
if (row !== 'meta') {
@@ -127,8 +142,9 @@ export const getManagedShops = async (user_id: number): Promise<Vendors> => {
} catch (err) {
throw err;
} finally {
// Return connection
await conn.end();
if (conn) {
conn.end();
}
}
return vendorRows;
@@ -141,8 +157,10 @@ export const getManagedShops = async (user_id: number): Promise<Vendors> => {
* @param product_id The product id of the product to deactivate the listing for
*/
export const deactivateListing = async (user_id: number, vendor_id: number, product_id: number): Promise<Boolean> => {
let conn = await BetterzonDB.getConnection();
let conn;
try {
conn = await pool.getConnection();
// Check if the user is authorized to manage the requested vendor
const user_vendor_rows = await conn.query('SELECT vendor_id FROM vendors WHERE vendor_id = ? AND admin_id = ?', [vendor_id, user_id]);
if (user_vendor_rows.length !== 1) {
@@ -155,9 +173,12 @@ export const deactivateListing = async (user_id: number, vendor_id: number, prod
} catch (err) {
throw err;
} finally {
// Return connection
await conn.end();
if (conn) {
conn.end();
}
}
return false;
};
/**
@@ -167,8 +188,10 @@ export const deactivateListing = async (user_id: number, vendor_id: number, prod
* @param isActive The new active state
*/
export const setShopStatus = async (user_id: number, vendor_id: number, isActive: boolean): Promise<Boolean> => {
let conn = await BetterzonDB.getConnection();
let conn;
try {
conn = await pool.getConnection();
// Check if the user is authorized to manage the requested vendor
const user_vendor_rows = await conn.query('SELECT vendor_id FROM vendors WHERE vendor_id = ? AND admin_id = ?', [vendor_id, user_id]);
if (user_vendor_rows.length !== 1) {
@@ -182,7 +205,10 @@ export const setShopStatus = async (user_id: number, vendor_id: number, isActive
} catch (err) {
throw err;
} finally {
// Return connection
await conn.end();
if (conn) {
conn.end();
}
}
return false;
};
@@ -1,19 +0,0 @@
import * as dotenv from 'dotenv';
const mariadb = require('mariadb');
dotenv.config();
export namespace ClimbingRouteRatingDB {
const pool = mariadb.createPool({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.CRR_DATABASE,
connectionLimit: 5
});
export const getConnection = async () => {
return pool.getConnection();
};
}
@@ -1,35 +0,0 @@
/**
* Required External Modules and Interfaces
*/
import express, {Request, Response} from 'express';
import {Guid} from 'guid-typescript';
import logger from '../../middleware/logger';
import {climbingGymRouter} from './climbing_gyms/climbingGyms.router';
import {climbingRoutesRouter} from './climbing_routes/climbingRoutes.router';
import {routeCommentsRouter} from './route_comments/routeComments.router';
import {routeRatingsRouter} from './route_ratings/routeRatings.router';
/**
* Router Definition
*/
export const crrRouter = express.Router();
// Sub-Endpoints
crrRouter.use('/gyms', climbingGymRouter);
crrRouter.use('/routes', climbingRoutesRouter);
crrRouter.use('/comments', routeCommentsRouter);
crrRouter.use('/ratings', routeRatingsRouter);
crrRouter.get('/', async (req: Request, res: Response) => {
try {
res.status(200).send('Pluto Development Climbing Route Rating API Endpoint');
} catch (e: any) {
let errorGuid = Guid.create().toString();
logger.error('Error handling a request: ' + e.message, {reference: errorGuid});
res.status(500).send({
'status': 'PROCESSING_ERROR',
'message': 'Internal Server Error. Try again later.',
'reference': errorGuid
});
}
});
@@ -1,6 +0,0 @@
export interface ClimbingGym {
gym_id: number;
name: string;
city: string;
verified: boolean;
}
@@ -1,152 +0,0 @@
/**
* Required External Modules and Interfaces
*/
import express, {Request, Response} from 'express';
import {Guid} from 'guid-typescript';
import logger from '../../../middleware/logger';
import {ClimbingGym} from './ClimbingGym.interface';
import * as GymService from './climbingGyms.service';
import {verifyCaptcha} from '../common/VerifyCaptcha';
/**
* Router Definition
*/
export const climbingGymRouter = express.Router();
/**
* @swagger
* /crr/gyms:
* get:
* summary: Retrieve all known climbing gyms
* description: Returns all climbing gyms in a JSON list
* tags:
* - climbing-route-rating
* responses:
* 200:
* description: Success
* content:
* application/json:
* schema:
* type: array
* items:
* type: object
* properties:
* gym_id:
* type: integer
* description: The gym id
* example: 1
* name:
* type: string
* description: The gym name
* example: DAV Kletterhalle
* city:
* type: string
* description: The city where the gym is in
* example: Karlsruhe
* verified:
* type: boolean
* description: If the gym is verified
* example: 1
* 500:
* description: A server error occurred. Please try again. If this issue persists, contact the admin.
*/
climbingGymRouter.get('/', async (req: Request, res: Response) => {
try {
const gyms: ClimbingGym[] = await GymService.findAll();
res.status(200).send(gyms);
} catch (e: any) {
let errorGuid = Guid.create().toString();
logger.error('Error handling a request: ' + e.message, {reference: errorGuid});
res.status(500).send({
'status': 'PROCESSING_ERROR',
'message': 'Internal Server Error. Try again later.',
'reference': errorGuid
});
}
});
/**
* @swagger
* /crr/gyms:
* post:
* summary: Create a new climbing gym
* description: Creates a new climbing gym and returns the id of the created gym
* tags:
* - climbing-route-rating
* responses:
* 201:
* description: Created
* content:
* application/json:
* schema:
* type: object
* properties:
* gym_id:
* type: integer
* description: The gym id
* example: 1
* 400:
* description: Wrong parameters, see response body for detailed information
* 403:
* description: Invalid captcha, please try again.
* 500:
* description: A server error occurred. Please try again. If this issue persists, contact the admin.
* parameters:
* - in: query
* name: name
* required: true
* description: The name of the gym
* schema:
* type: string
* example: DAV Kletterhalle
* - in: query
* name: city
* required: true
* description: The city where the gym is in
* schema:
* type: string
* example: Karlsruhe
* - in: query
* name: hcaptcha_response
* required: true
* description: The hCaptcha response key
* schema:
* type: string
* example: P0_ey[...]bVu
*/
climbingGymRouter.post('/', async (req: Request, res: Response) => {
try {
let name = req.query.name as string;
let city = req.query.city as string;
let captcha_token = req.query['hcaptcha_response'] as string;
if (!name || !city || !captcha_token) {
res.status(400).send({'message': 'Missing parameters'});
return;
}
// Verify captcha
let success = await verifyCaptcha(captcha_token);
if (!success) {
res.status(403).send({'message': 'Invalid Captcha. Please try again.'});
return;
}
let result = await GymService.createGym(name, city);
if (result) {
res.status(201).send({'gym_id': result});
} else {
res.status(500).send({});
}
} catch (e: any) {
let errorGuid = Guid.create().toString();
logger.error('Error handling a request: ' + e.message, {reference: errorGuid});
res.status(500).send({
'status': 'PROCESSING_ERROR',
'message': 'Internal Server Error. Try again later.',
'reference': errorGuid
});
}
});
@@ -1,39 +0,0 @@
import {ClimbingRouteRatingDB} from '../ClimbingRouteRating.db';
import {ClimbingGym} from './ClimbingGym.interface';
/**
* Fetches and returns all known climbing gyms
* @return Promise<ClimbingHall[]> The climbing halls
*/
export const findAll = async (): Promise<ClimbingGym[]> => {
let conn = await ClimbingRouteRatingDB.getConnection();
try {
return await conn.query('SELECT gym_id, name, city, verified FROM climbing_gyms');
} catch (err) {
throw err;
} finally {
// Return connection
await conn.end();
}
};
/**
* Creates a climbing gym and returns the id of the created gym
* @param name The name of the climbing hall
* @param city The city of the climbing hall
* @return number The id of the climbing hall
*/
export const createGym = async (name: string, city: string): Promise<number> => {
let conn = await ClimbingRouteRatingDB.getConnection();
try {
let res = await conn.query('INSERT INTO climbing_gyms (name, city) VALUES (?, ?) RETURNING gym_id', [name, city]);
return res[0].gym_id;
} catch (err) {
throw err;
} finally {
// Return connection
await conn.end();
}
};
@@ -1,7 +0,0 @@
export interface ClimbingRoute {
route_id: string;
gym_id: number;
name: string;
difficulty: string;
route_setting_date: Date;
}
@@ -1,226 +0,0 @@
/**
* Required External Modules and Interfaces
*/
import express, {Request, Response} from 'express';
import {Guid} from 'guid-typescript';
import logger from '../../../middleware/logger';
import {ClimbingRoute} from './ClimbingRoute.interface';
import * as RouteService from './climbingRoutes.service';
import {verifyCaptcha} from '../common/VerifyCaptcha';
/**
* Router Definition
*/
export const climbingRoutesRouter = express.Router();
/**
* @swagger
* /crr/routes:
* get:
* summary: Retrieve all known climbing routes
* description: Returns all climbing routes in a JSON list
* tags:
* - climbing-route-rating
* responses:
* 200:
* description: Success
* content:
* application/json:
* schema:
* type: array
* items:
* type: object
* properties:
* route_id:
* type: string
* description: The route id
* example: duck-score-guide
* gym_id:
* type: integer
* description: The id of the gym that the route belongs to
* example: 1
* name:
* type: string
* description: The route name
* example: Mary Poppins
* difficulty:
* type: string
* description: The difficulty of the route
* example: 'DE: 5, FR: 5c'
* route_setting_date:
* type: datetime
* description: The route setting date
* example: 2022-01-07T23:00:00.000Z
* 500:
* description: A server error occurred. Please try again. If this issue persists, contact the admin.
*/
climbingRoutesRouter.get('/', async (req: Request, res: Response) => {
try {
const routes: ClimbingRoute[] = await RouteService.findAll();
res.status(200).send(routes);
} catch (e: any) {
let errorGuid = Guid.create().toString();
logger.error('Error handling a request: ' + e.message, {reference: errorGuid});
res.status(500).send({
'status': 'PROCESSING_ERROR',
'message': 'Internal Server Error. Try again later.',
'reference': errorGuid
});
}
});
/**
* @swagger
* /crr/routes/{id}:
* get:
* summary: Retrieve the route with the given id
* description: Returns the climbing route with the given id if it exists
* tags:
* - climbing-route-rating
* responses:
* 200:
* description: Success
* content:
* application/json:
* schema:
* type: array
* items:
* type: object
* properties:
* route_id:
* type: string
* description: The route id
* example: duck-score-guide
* gym_id:
* type: integer
* description: The id of the gym that the route belongs to
* example: 1
* name:
* type: string
* description: The route name
* example: Mary Poppins
* difficulty:
* type: string
* description: The difficulty of the route
* example: 'DE: 5, FR: 5c'
* route_setting_date:
* type: datetime
* description: The route setting date
* example: 2022-01-07T23:00:00.000Z
* 500:
* description: A server error occurred. Please try again. If this issue persists, contact the admin.
* parameters:
* - in: path
* name: id
* required: true
* description: The id of the route
* schema:
* type: string
* example: duck-score-guide
*/
climbingRoutesRouter.get('/:id', async (req: Request, res: Response) => {
try {
let route_id = req.params.id;
const route: ClimbingRoute = await RouteService.findById(route_id);
res.status(200).send(route);
} catch (e: any) {
let errorGuid = Guid.create().toString();
logger.error('Error handling a request: ' + e.message, {reference: errorGuid});
res.status(500).send({
'status': 'PROCESSING_ERROR',
'message': 'Internal Server Error. Try again later.',
'reference': errorGuid
});
}
});
/**
* @swagger
* /crr/routes:
* post:
* summary: Create a new climbing route
* description: Creates a new climbing route and returns the id of the created route
* tags:
* - climbing-route-rating
* responses:
* 201:
* description: Created
* content:
* application/json:
* schema:
* type: object
* properties:
* route_id:
* type: string
* description: The route id
* example: duck-score-guide
* 400:
* description: Wrong parameters, see response body for detailed information
* 403:
* description: Invalid captcha, please try again.
* 500:
* description: A server error occurred. Please try again. If this issue persists, contact the admin.
* parameters:
* - in: query
* name: gym_id
* required: true
* description: The gym id of the gym that the route belongs to
* schema:
* type: integer
* example: 1
* - in: query
* name: name
* required: true
* description: The name of the route
* schema:
* type: string
* example: Mary Poppins
* - in: query
* name: difficulty
* required: true
* description: The difficulty of the route
* schema:
* type: string
* example: 'DE: 5, FR: 5c'
* - in: query
* name: hcaptcha_response
* required: true
* description: The hCaptcha response key
* schema:
* type: string
* example: P0_ey[...]bVu
*/
climbingRoutesRouter.post('/', async (req: Request, res: Response) => {
try {
let gym_id = Number(req.query.gym_id);
let name = req.query.name as string;
let difficulty = req.query.difficulty as string;
let captcha_token = req.query['hcaptcha_response'] as string;
if (isNaN(gym_id) || !name || !difficulty || !captcha_token) {
res.status(400).send({'message': 'Missing parameters'});
return;
}
// Verify captcha
if (!await verifyCaptcha(captcha_token)) {
res.status(403).send({'message': 'Invalid Captcha. Please try again.'});
return;
}
let route_id = await RouteService.createRoute(gym_id, name, difficulty);
res.status(201).send({'route_id': route_id});
} catch (e: any) {
let errorGuid = Guid.create().toString();
logger.error('Error handling a request: ' + e.message, {reference: errorGuid});
res.status(500).send({
'status': 'PROCESSING_ERROR',
'message': 'Internal Server Error. Try again later.',
'reference': errorGuid
});
}
});
@@ -1,68 +0,0 @@
import {ClimbingRouteRatingDB} from '../ClimbingRouteRating.db';
import {ClimbingRoute} from './ClimbingRoute.interface';
import random from 'random-words';
/**
* Fetches and returns all known climbing routes
* @return Promise<ClimbingRoute[]> The climbing routes
*/
export const findAll = async (): Promise<ClimbingRoute[]> => {
let conn = await ClimbingRouteRatingDB.getConnection();
try {
return await conn.query('SELECT route_id, gym_id, name, difficulty, route_setting_date FROM climbing_routes');
} catch (err) {
throw err;
} finally {
// Return connection
await conn.end();
}
};
/**
* Fetches and returns information about the given route
* @param route_id The id of the route
* @return Promise<ClimbingRoute> The climbing route
*/
export const findById = async (route_id: string): Promise<ClimbingRoute> => {
let conn = await ClimbingRouteRatingDB.getConnection();
try {
return await conn.query('SELECT route_id, gym_id, name, difficulty, route_setting_date FROM climbing_routes WHERE route_id = ?', route_id);
} catch (err) {
throw err;
} finally {
// Return connection
await conn.end();
}
};
/**
* Creates a new route and returns the id of the created route
* @param gym_id The id of the climbing gym that the route belongs to
* @param name The name of the climbing route
* @param difficulty The difficulty of the climbing route
* @return string The id of the created route
*/
export const createRoute = async (gym_id: number, name: string, difficulty: string): Promise<string> => {
let conn = await ClimbingRouteRatingDB.getConnection();
// Generate route id
let route_id = '';
let randWords = random(3);
for (let i = 0; i <= 2; i++) {
route_id += randWords[i];
if (i < 2) {
route_id += '-';
}
}
try {
await conn.query('INSERT INTO climbing_routes (route_id, gym_id, name, difficulty) VALUES (?, ?, ?, ?)', [route_id, gym_id, name, difficulty]);
return route_id;
} catch (err) {
throw err;
} finally {
// Return connection
await conn.end();
}
};
@@ -1,15 +0,0 @@
import * as dotenv from 'dotenv';
import * as querystring from 'qs';
import axios from 'axios';
dotenv.config();
export const verifyCaptcha = async (captcha_token: string): Promise<boolean> => {
let postData = querystring.stringify({
response: captcha_token,
secret: process.env.HCAPTCHA_SECRET
});
let res = await axios.post('https://hcaptcha.com/siteverify', postData);
return res.data.success;
};
@@ -1,6 +0,0 @@
export interface RouteComment {
comment_id: number;
route_id: string;
comment: string;
timestamp: Date;
}
@@ -1,155 +0,0 @@
import express, {Request, Response} from 'express';
import * as CommentService from './routeComments.service';
import {Guid} from 'guid-typescript';
import logger from '../../../middleware/logger';
import {RouteComment} from './RouteComment.interface';
import {verifyCaptcha} from '../common/VerifyCaptcha';
export const routeCommentsRouter = express.Router();
/**
* @swagger
* /crr/comments/by/route/{id}:
* get:
* summary: Retrieve the comments for the given route
* description: Returns all comments for the route with the specified id
* tags:
* - climbing-route-rating
* responses:
* 200:
* description: Success
* content:
* application/json:
* schema:
* type: array
* items:
* type: object
* properties:
* comment_id:
* type: integer
* description: The comment id
* example: 2
* route_id:
* type: string
* description: The id of the route that the comment belongs to
* example: duck-score-guide
* comment:
* type: string
* description: The comment text
* example: Nice route! Was a lot of fun!
* timestamp:
* type: datetime
* description: The time when the comment was sent
* example: 2022-01-08T21:43:31.000Z
* 500:
* description: A server error occurred. Please try again. If this issue persists, contact the admin.
* parameters:
* - in: path
* name: id
* required: true
* description: The id of the route
* schema:
* type: string
* example: duck-score-guide
*/
routeCommentsRouter.get('/by/route/:id', async (req: Request, res: Response) => {
try {
let route_id = req.params.id;
const comments: RouteComment[] = await CommentService.findByRoute(route_id);
res.status(200).send(comments);
} catch (e: any) {
let errorGuid = Guid.create().toString();
logger.error('Error handling a request: ' + e.message, {reference: errorGuid});
res.status(500).send({
'status': 'PROCESSING_ERROR',
'message': 'Internal Server Error. Try again later.',
'reference': errorGuid
});
}
});
/**
* @swagger
* /crr/comments:
* post:
* summary: Create a new comment
* description: Creates a new comment and returns the id of the created comment
* tags:
* - climbing-route-rating
* responses:
* 201:
* description: Created
* content:
* application/json:
* schema:
* type: object
* properties:
* comment_id:
* type: integer
* description: The comment id
* example: 1
* 400:
* description: Wrong parameters, see response body for detailed information
* 403:
* description: Invalid captcha, please try again.
* 500:
* description: A server error occurred. Please try again. If this issue persists, contact the admin.
* parameters:
* - in: query
* name: route_id
* required: true
* description: The id of the route to create the comment for
* schema:
* type: string
* example: duck-score-guide
* - in: query
* name: comment
* required: true
* description: The comment text
* schema:
* type: string
* example: Nice route! Was a lot of fun!
* - in: query
* name: hcaptcha_response
* required: true
* description: The hCaptcha response key
* schema:
* type: string
* example: P0_ey[...]bVu
*/
routeCommentsRouter.post('/', async (req: Request, res: Response) => {
try {
let route_id = req.query.route_id as string;
let comment = req.query.comment as string;
let captcha_token = req.query['hcaptcha_response'] as string;
if (!route_id || !comment || !captcha_token) {
res.status(400).send({'message': 'Missing parameters'});
return;
}
// Verify captcha
if (!await verifyCaptcha(captcha_token)) {
res.status(403).send({'message': 'Invalid Captcha. Please try again.'});
return;
}
let result = await CommentService.createComment(route_id, comment);
if (result) {
res.status(201).send({'comment_id': result});
} else {
res.status(500).send({});
}
} catch (e: any) {
let errorGuid = Guid.create().toString();
logger.error('Error handling a request: ' + e.message, {reference: errorGuid});
res.status(500).send({
'status': 'PROCESSING_ERROR',
'message': 'Internal Server Error. Try again later.',
'reference': errorGuid
});
}
});
@@ -1,38 +0,0 @@
import {ClimbingRouteRatingDB} from '../ClimbingRouteRating.db';
import {RouteComment} from './RouteComment.interface';
/**
* Fetches and returns all comments that belong to the given route
* @return Promise<RouteComment[]> The comments
*/
export const findByRoute = async (route_id: string): Promise<RouteComment[]> => {
let conn = await ClimbingRouteRatingDB.getConnection();
try {
return await conn.query('SELECT comment_id, route_id, comment, timestamp FROM route_comments WHERE route_id = ?', route_id);
} catch (err) {
throw err;
} finally {
// Return connection
await conn.end();
}
};
/**
* Creates a new comment and returns the id of the created comment
* @param route_id The id of the route to create the comment for
* @param comment The comment
* @return number The id of the comment
*/
export const createComment = async (route_id: string, comment: string): Promise<number> => {
let conn = await ClimbingRouteRatingDB.getConnection();
try {
let res = await conn.query('INSERT INTO route_comments (route_id, comment) VALUES (?, ?) RETURNING comment_id', [route_id, comment]);
return res[0].comment_id;
} catch (err) {
throw err;
} finally {
// Return connection
await conn.end();
}
};
@@ -1,6 +0,0 @@
export interface RouteRating {
rating_id: number;
route_id: string;
stars: number;
timestamp: Date;
}
@@ -1,140 +0,0 @@
import express, {Request, Response} from 'express';
import * as RatingService from './routeRatings.service';
import {Guid} from 'guid-typescript';
import logger from '../../../middleware/logger';
import {verifyCaptcha} from '../common/VerifyCaptcha';
export const routeRatingsRouter = express.Router();
/**
* @swagger
* /crr/ratings/by/route/{id}:
* get:
* summary: Retrieve the rating for the given route
* description: Returns the medium amount of stars that the route got
* tags:
* - climbing-route-rating
* responses:
* 200:
* description: Success
* content:
* application/json:
* schema:
* type: object
* properties:
* rating:
* type: float
* description: The median amount of stars
* example: 4.5
* 500:
* description: A server error occurred. Please try again. If this issue persists, contact the admin.
* parameters:
* - in: path
* name: id
* required: true
* description: The id of the route
* schema:
* type: string
* example: duck-score-guide
*/
routeRatingsRouter.get('/by/route/:id', async (req: Request, res: Response) => {
try {
let route_id = req.params.id;
let rating = await RatingService.getStarsForRoute(route_id);
res.status(200).send({'rating': rating});
} catch (e: any) {
let errorGuid = Guid.create().toString();
logger.error('Error handling a request: ' + e.message, {reference: errorGuid});
res.status(500).send({
'status': 'PROCESSING_ERROR',
'message': 'Internal Server Error. Try again later.',
'reference': errorGuid
});
}
});
/**
* @swagger
* /crr/ratings:
* post:
* summary: Create a new rating
* description: Creates a new rating and returns the id of the created rating
* tags:
* - climbing-route-rating
* responses:
* 201:
* description: Created
* content:
* application/json:
* schema:
* type: object
* properties:
* rating_id:
* type: integer
* description: The rating id
* example: 1
* 400:
* description: Wrong parameters, see response body for detailed information
* 403:
* description: Invalid captcha, please try again.
* 500:
* description: A server error occurred. Please try again. If this issue persists, contact the admin.
* parameters:
* - in: query
* name: route_id
* required: true
* description: The id of the route to create the rating for
* schema:
* type: string
* example: duck-score-guide
* - in: query
* name: stars
* required: true
* description: The amount of stars to give
* schema:
* type: integer
* example: 4
* - in: query
* name: hcaptcha_response
* required: true
* description: The hCaptcha response key
* schema:
* type: string
* example: P0_ey[...]bVu
*/
routeRatingsRouter.post('/', async (req: Request, res: Response) => {
try {
let route_id = req.query.route_id as string;
let stars = Number(req.query.stars);
let captcha_token = req.query['hcaptcha_response'] as string;
if (!route_id || isNaN(stars) || !captcha_token) {
res.status(400).send({'message': 'Missing parameters'});
return;
}
// Verify captcha
if (!await verifyCaptcha(captcha_token)) {
res.status(403).send({'message': 'Invalid Captcha. Please try again.'});
return;
}
let result = await RatingService.createRating(route_id, stars);
if (result) {
res.status(201).send({'rating_id': result});
} else {
res.status(500).send({});
}
} catch (e: any) {
let errorGuid = Guid.create().toString();
logger.error('Error handling a request: ' + e.message, {reference: errorGuid});
res.status(500).send({
'status': 'PROCESSING_ERROR',
'message': 'Internal Server Error. Try again later.',
'reference': errorGuid
});
}
});
@@ -1,58 +0,0 @@
import {ClimbingRouteRatingDB} from '../ClimbingRouteRating.db';
import {RouteRating} from './RouteRating.interface';
/**
* Fetches and returns all ratings for the given route
* @param route_id The id of the route to get the ratings for
* @return Promise<RouteRating[]> The ratings
*/
export const findByRoute = async (route_id: string): Promise<RouteRating[]> => {
let conn = await ClimbingRouteRatingDB.getConnection();
try {
return await conn.query('SELECT rating_id, route_id, stars, timestamp FROM route_ratings WHERE route_id = ?', route_id);
} catch (err) {
throw err;
} finally {
// Return connection
await conn.end();
}
};
/**
* Get the median amount of stars the given route got from climbers
* @param route_id The id of the route to get the rating for
* @return number The median amount of stars with 1 fraction digit.
*/
export const getStarsForRoute = async (route_id: string): Promise<number> => {
let ratings = await findByRoute(route_id);
let starsSum = 0;
let starsAmount = 0;
for (let rating of ratings) {
starsSum += rating.stars;
starsAmount++;
}
return Number((starsSum / starsAmount).toFixed(1));
};
/**
* Creates a new rating and returns the id
* @param route_id The id of the route to be rated
* @param stars The amount of stars to be given
* @return number The id of the created rating
*/
export const createRating = async (route_id: string, stars: number): Promise<number> => {
let conn = await ClimbingRouteRatingDB.getConnection();
try {
let res = await conn.query('INSERT INTO route_ratings (route_id, stars) VALUES (?, ?) RETURNING rating_id', [route_id, stars]);
return res[0].comment_id;
} catch (err) {
throw err;
} finally {
// Return connection
await conn.end();
}
};
@@ -1,19 +0,0 @@
import * as dotenv from 'dotenv';
const mariadb = require('mariadb');
dotenv.config();
export namespace RaPlaChangesDB {
const pool = mariadb.createPool({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.RAPLACHANGES_DATABASE,
connectionLimit: 5
});
export const getConnection = async () => {
return pool.getConnection();
};
}
@@ -18,7 +18,7 @@ dhbwRaPlaChangesRouter.get('/', async (req: Request, res: Response) => {
let changes = await ChangeService.getChanges('TINF19B4', week);
res.status(200).send(changes);
} catch (e: any) {
} catch (e) {
let errorGuid = Guid.create().toString();
logger.error('Error handling a request: ' + e.message, {reference: errorGuid});
res.status(500).send({
@@ -36,7 +36,7 @@ dhbwRaPlaChangesRouter.get('/:id', async (req: Request, res: Response) => {
let changes = await ChangeService.getEventById('TINF19B4', id);
res.status(200).send(changes);
} catch (e: any) {
} catch (e) {
let errorGuid = Guid.create().toString();
logger.error('Error handling a request: ' + e.message, {reference: errorGuid});
res.status(500).send({
@@ -1,13 +1,23 @@
import * as dotenv from 'dotenv';
import {Event} from './Event.interface';
import {Change} from './Change.interface';
import {RaPlaChangesDB} from '../DHBWRaPlaChanges.db';
dotenv.config();
const mariadb = require('mariadb');
const pool = mariadb.createPool({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.RAPLACHANGES_DATABASE,
connectionLimit: 5
});
export const getChanges = async (course: string, week: string): Promise<Event[]> => {
let conn = await RaPlaChangesDB.getConnection();
let conn;
try {
conn = await pool.getConnection();
let relevantEventsRows = await conn.query('SELECT DISTINCT(entry_id) FROM rapla_changes WHERE new_start > ? AND new_start < DATE_ADD(?, INTERVAL 7 DAY)', [week, week]);
let relevantEventIds: string[] = [];
@@ -69,14 +79,17 @@ export const getChanges = async (course: string, week: string): Promise<Event[]>
} catch (err) {
throw err;
} finally {
// Return connection
await conn.end();
if (conn) {
conn.end();
}
}
};
export const getEventById = async (course: string, id: string): Promise<Event> => {
let conn = await RaPlaChangesDB.getConnection();
let conn;
try {
conn = await pool.getConnection();
let rows = await conn.query('SELECT c.change_id, c.entry_id, c.change_timestamp, c.isDeleted, c.new_summary, c.new_description, c.new_start, c.new_last_modified, c.new_end, c.new_created, c.new_location, c.new_organizer, c.new_categories, e.uid FROM rapla_changes c LEFT OUTER JOIN rapla_entries e ON c.entry_id = e.entry_id WHERE e.uid = ? ORDER BY c.change_id', id);
let eventsMap = new Map();
@@ -127,7 +140,8 @@ export const getEventById = async (course: string, id: string): Promise<Event> =
} catch (err) {
throw err;
} finally {
// Return connection
await conn.end();
if (conn) {
conn.end();
}
}
};
@@ -17,7 +17,7 @@ dhbwServiceRouter.use('/generalInfo', generalInfoRouter);
dhbwServiceRouter.get('/', async (req: Request, res: Response) => {
try {
res.status(200).send('Pluto Development DHBW Service App API Endpoint');
} catch (e: any) {
} catch (e) {
let errorGuid = Guid.create().toString();
logger.error('Error handling a request: ' + e.message, {reference: errorGuid});
res.status(500).send({
@@ -13,7 +13,7 @@ export const generalInfoRouter = express.Router();
generalInfoRouter.get('/', async (req: Request, res: Response) => {
try {
res.status(200).send('GET generalInfo v2.1');
} catch (e: any) {
} catch (e) {
let errorGuid = Guid.create().toString();
logger.error('Error handling a request: ' + e.message, {reference: errorGuid});
res.status(500).send({
@@ -27,7 +27,7 @@ generalInfoRouter.get('/', async (req: Request, res: Response) => {
generalInfoRouter.post('/', async (req: Request, res: Response) => {
try {
res.status(200).send('POST generalInfo v2.1');
} catch (e: any) {
} catch (e) {
let errorGuid = Guid.create().toString();
logger.error('Error handling a request: ' + e.message, {reference: errorGuid});
res.status(500).send({
-29
View File
@@ -1,29 +0,0 @@
import * as dotenv from 'dotenv';
const mariadb = require('mariadb');
dotenv.config();
export namespace PartyPlanerDB {
const prod_pool = mariadb.createPool({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.PARTYPLANER_PROD_DATABASE,
connectionLimit: 5
});
const dev_pool = mariadb.createPool({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.PARTYPLANER_DEV_DATABASE,
connectionLimit: 5
});
export const getConnection = async (useDev: boolean = false) => {
if (useDev) {
return dev_pool.getConnection();
}
return prod_pool.getConnection();
};
}
+1 -1
View File
@@ -29,7 +29,7 @@ partyPlanerRouter.use('/user', userRouter);
partyPlanerRouter.get('/', async (req: Request, res: Response) => {
try {
res.status(200).send('Pluto Development PartyPlaner API Endpoint V2');
} catch (e: any) {
} catch (e) {
let errorGuid = Guid.create().toString();
logger.error('Error handling a request: ' + e.message, {reference: errorGuid});
res.status(500).send({
+2 -1
View File
@@ -14,6 +14,7 @@ export const eventRouter = express.Router();
eventRouter.get('/:isDevCall', async (req: Request, res: Response) => {
try {
throw new Error('Test');
let userId = (req.query.userId ?? '').toString();
let sessionId = (req.query.sessionId ?? '').toString();
let sessionKey = (req.query.sessionKey ?? '').toString();
@@ -38,7 +39,7 @@ eventRouter.get('/:isDevCall', async (req: Request, res: Response) => {
let data = await EventService.getEventData(useDev, userId);
res.status(200).send(data);
} catch (e: any) {
} catch (e) {
let errorGuid = Guid.create().toString();
logger.error('Error handling a request: ' + e.message, {reference: errorGuid});
res.status(500).send({
+26 -4
View File
@@ -1,9 +1,24 @@
import * as dotenv from 'dotenv';
import {Event} from './Event.interface';
import {PartyPlanerDB} from '../PartyPlaner.db';
dotenv.config();
const mariadb = require('mariadb');
const prod_pool = mariadb.createPool({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.PARTYPLANER_PROD_DATABASE,
connectionLimit: 5
});
const dev_pool = mariadb.createPool({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.PARTYPLANER_DEV_DATABASE,
connectionLimit: 5
});
/**
* Returns all events of the given user
* @param useDev If the dev or prod database should be used
@@ -11,8 +26,14 @@ dotenv.config();
* @return Event[] A list of events
*/
export const getEventData = async (useDev: boolean, userId: string): Promise<Event[]> => {
let conn = await PartyPlanerDB.getConnection(useDev);
let conn;
try {
if (useDev) {
conn = await dev_pool.getConnection();
} else {
conn = await prod_pool.getConnection();
}
let eventRows = await conn.query('SELECT event_id, name, description, takes_place_date, registration_until_date, max_participants FROM events WHERE creator_id = ?', userId);
let eventsMap = new Map<string, Event>();
@@ -70,7 +91,8 @@ export const getEventData = async (useDev: boolean, userId: string): Promise<Eve
} catch (err) {
throw err;
} finally {
// Return connection
await conn.end();
if (conn) {
conn.end();
}
}
};
@@ -38,7 +38,7 @@ friendshipRouter.get('/:isDevCall', async (req: Request, res: Response) => {
let data = await FriendshipService.getFriendshipData(useDev, userId);
res.status(200).send(data);
} catch (e: any) {
} catch (e) {
let errorGuid = Guid.create().toString();
logger.error('Error handling a request: ' + e.message, {reference: errorGuid});
res.status(500).send({
@@ -1,9 +1,24 @@
import * as dotenv from 'dotenv';
import {Friendship} from './Friendship.interface';
import {PartyPlanerDB} from '../PartyPlaner.db';
dotenv.config();
const mariadb = require('mariadb');
const prod_pool = mariadb.createPool({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.PARTYPLANER_PROD_DATABASE,
connectionLimit: 5
});
const dev_pool = mariadb.createPool({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.PARTYPLANER_DEV_DATABASE,
connectionLimit: 5
});
/**
* Returns all friends of the given user
* @param useDev If the dev or prod database should be used
@@ -11,8 +26,14 @@ dotenv.config();
* @return Friendship[] A list of friends
*/
export const getFriendshipData = async (useDev: boolean, userId: string): Promise<Friendship[]> => {
let conn = await PartyPlanerDB.getConnection(useDev);
let conn;
try {
if (useDev) {
conn = await dev_pool.getConnection();
} else {
conn = await prod_pool.getConnection();
}
let rows = await conn.query('SELECT f.friendship_id, f.friend_id, u.first_name as friend_first_name, u.last_name as friend_last_name, u.username as friend_username FROM friendships f LEFT OUTER JOIN users u ON f.friend_id = u.user_id WHERE f.user_id = ?', userId);
let friends: Friendship[] = [];
@@ -31,7 +52,8 @@ export const getFriendshipData = async (useDev: boolean, userId: string): Promis
} catch (err) {
throw err;
} finally {
// Return connection
await conn.end();
if (conn) {
conn.end();
}
}
};
@@ -38,7 +38,7 @@ inviteRouter.get('/:isDevCall', async (req: Request, res: Response) => {
let data = await InviteService.getInvitesData(useDev, userId);
res.status(200).send(data);
} catch (e: any) {
} catch (e) {
let errorGuid = Guid.create().toString();
logger.error('Error handling a request: ' + e.message, {reference: errorGuid});
res.status(500).send({
@@ -1,9 +1,24 @@
import * as dotenv from 'dotenv';
import {ReceivedInvite} from './ReceivedInvite.interface';
import {PartyPlanerDB} from '../PartyPlaner.db';
dotenv.config();
const mariadb = require('mariadb');
const prod_pool = mariadb.createPool({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.PARTYPLANER_PROD_DATABASE,
connectionLimit: 5
});
const dev_pool = mariadb.createPool({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.PARTYPLANER_DEV_DATABASE,
connectionLimit: 5
});
/**
* Returns all events the user is invited to
* @param useDev If the dev or prod database should be used
@@ -11,8 +26,14 @@ dotenv.config();
* @return ReceivedInvite[] A list of invites
*/
export const getInvitesData = async (useDev: boolean, userId: string): Promise<ReceivedInvite[]> => {
let conn = await PartyPlanerDB.getConnection(useDev);
let conn;
try {
if (useDev) {
conn = await dev_pool.getConnection();
} else {
conn = await prod_pool.getConnection();
}
let rows = await conn.query('SELECT i.invite_id, i.valid_until, i.already_used, i.invite_key, e.name as event_name, e.description as event_description, e.takes_place_date, e.registration_until_date, e.max_participants, e.creator_id, u.first_name, u.last_name FROM invitations i LEFT OUTER JOIN events e ON e.event_id = i.event_id LEFT OUTER JOIN users u ON u.user_id = e.creator_id WHERE i.user_id = ?', userId);
let invites: ReceivedInvite[] = [];
@@ -38,7 +59,8 @@ export const getInvitesData = async (useDev: boolean, userId: string): Promise<R
} catch (err) {
throw err;
} finally {
// Return connection
await conn.end();
if (conn) {
conn.end();
}
}
};
+1 -1
View File
@@ -58,7 +58,7 @@ loginRouter.post('/:isDevCall', async (req: Request, res: Response) => {
let session = await UserService.loginUser(useDev, username, email, password, userIP, deviceInfo);
res.status(200).send(session);
} catch (e: any) {
} catch (e) {
let errorGuid = Guid.create().toString();
logger.error('Error handling a request: ' + e.message, {reference: errorGuid});
res.status(500).send({
@@ -77,7 +77,7 @@ registerRouter.post('/:isDevCall', async (req: Request, res: Response) => {
let session = await UserService.registerUser(useDev, username, email, firstName, lastName, password, userIP, deviceInfo);
res.status(201).send(session);
} catch (e: any) {
} catch (e) {
let errorGuid = Guid.create().toString();
logger.error('Error handling a request: ' + e.message, {reference: errorGuid});
res.status(500).send({
@@ -38,7 +38,7 @@ sessionRouter.get('/:isDevCall', async (req: Request, res: Response) => {
let data = await SessionService.getSessionData(useDev, userId);
res.status(200).send(data);
} catch (e: any) {
} catch (e) {
let errorGuid = Guid.create().toString();
logger.error('Error handling a request: ' + e.message, {reference: errorGuid});
res.status(500).send({
@@ -1,9 +1,24 @@
import * as dotenv from 'dotenv';
import {SessionData} from './SessionData.interface';
import {PartyPlanerDB} from '../PartyPlaner.db';
dotenv.config();
const mariadb = require('mariadb');
const prod_pool = mariadb.createPool({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.PARTYPLANER_PROD_DATABASE,
connectionLimit: 5
});
const dev_pool = mariadb.createPool({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.PARTYPLANER_DEV_DATABASE,
connectionLimit: 5
});
/**
* Returns all active sessions of the given user
* @param useDev If the dev or prod database should be used
@@ -11,8 +26,14 @@ dotenv.config();
* @return SessionData[] A list containing objects with the session data
*/
export const getSessionData = async (useDev: boolean, userId: string): Promise<SessionData[]> => {
let conn = await PartyPlanerDB.getConnection(useDev);
let conn;
try {
if (useDev) {
conn = await dev_pool.getConnection();
} else {
conn = await prod_pool.getConnection();
}
let rows = await conn.query('SELECT session_id, type, last_login, last_ip FROM sessions WHERE user_id = ? AND valid_until > NOW()', userId);
let sessions: SessionData[] = [];
@@ -30,7 +51,8 @@ export const getSessionData = async (useDev: boolean, userId: string): Promise<S
} catch (err) {
throw err;
} finally {
// Return connection
await conn.end();
if (conn) {
conn.end();
}
}
};
+1 -1
View File
@@ -37,7 +37,7 @@ userRouter.get('/:isDevCall', async (req: Request, res: Response) => {
let data = await UserService.getUserData(useDev, userId);
res.status(200).send(data);
} catch (e: any) {
} catch (e) {
let errorGuid = Guid.create().toString();
logger.error('Error handling a request: ' + e.message, {reference: errorGuid});
res.status(500).send({
+75 -19
View File
@@ -4,10 +4,25 @@ import {Guid} from 'guid-typescript';
import {UserData} from './UserData.interface';
import {Session} from './Session.interface';
import {Status} from './Status.interface';
import {PartyPlanerDB} from '../PartyPlaner.db';
dotenv.config();
const mariadb = require('mariadb');
const prod_pool = mariadb.createPool({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.PARTYPLANER_PROD_DATABASE,
connectionLimit: 5
});
const dev_pool = mariadb.createPool({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.PARTYPLANER_DEV_DATABASE,
connectionLimit: 5
});
/**
* Returns all data about the given user
* @param useDev If the dev or prod database should be used
@@ -15,8 +30,14 @@ dotenv.config();
* @return UserData An object containing the user data
*/
export const getUserData = async (useDev: boolean, userId: string): Promise<UserData> => {
let conn = await PartyPlanerDB.getConnection(useDev);
let conn;
try {
if (useDev) {
conn = await dev_pool.getConnection();
} else {
conn = await prod_pool.getConnection();
}
let rows = await conn.query('SELECT username, email, first_name, last_Name, last_login, email_is_verified, is_premium_user FROM users WHERE user_id = ?', userId);
let user: UserData = {} as UserData;
@@ -37,8 +58,9 @@ export const getUserData = async (useDev: boolean, userId: string): Promise<User
} catch (err) {
throw err;
} finally {
// Return connection
await conn.end();
if (conn) {
conn.end();
}
}
};
@@ -48,8 +70,14 @@ export const getUserData = async (useDev: boolean, userId: string): Promise<User
* @return any An object with a list of usernames and emails
*/
export const getExistingUsernamesAndEmails = async (useDev: boolean): Promise<any> => {
let conn = await PartyPlanerDB.getConnection(useDev);
let conn;
try {
if (useDev) {
conn = await dev_pool.getConnection();
} else {
conn = await prod_pool.getConnection();
}
const rows = await conn.query('SELECT username, email FROM users');
let usernames: string[] = [];
@@ -67,8 +95,9 @@ export const getExistingUsernamesAndEmails = async (useDev: boolean): Promise<an
} catch (err) {
throw err;
} finally {
// Return connection
await conn.end();
if (conn) {
conn.end();
}
}
};
@@ -84,8 +113,14 @@ export const getExistingUsernamesAndEmails = async (useDev: boolean): Promise<an
* @param deviceInfo The user agent of the new user
*/
export const registerUser = async (useDev: boolean, username: string, email: string, firstName: string, lastName: string, password: string, ip: string, deviceInfo: string): Promise<Session> => {
let conn = await PartyPlanerDB.getConnection(useDev);
let conn;
try {
if (useDev) {
conn = await dev_pool.getConnection();
} else {
conn = await prod_pool.getConnection();
}
const pwHash = bcrypt.hashSync(password, 10);
const sessionKey = Guid.create().toString();
const sessionKeyHash = bcrypt.hashSync(sessionKey, 10);
@@ -132,8 +167,9 @@ export const registerUser = async (useDev: boolean, username: string, email: str
} catch (err) {
throw err;
} finally {
// Return connection
await conn.end();
if (conn) {
conn.end();
}
}
};
@@ -147,8 +183,14 @@ export const registerUser = async (useDev: boolean, username: string, email: str
* @param deviceInfo The user agent of the new user
*/
export const loginUser = async (useDev: boolean, username: string, email: string, password: string, ip: string, deviceInfo: string): Promise<Session> => {
let conn = await PartyPlanerDB.getConnection(useDev);
let conn;
try {
if (useDev) {
conn = await dev_pool.getConnection();
} else {
conn = await prod_pool.getConnection();
}
let query_result;
// Get the saved hash
@@ -207,8 +249,9 @@ export const loginUser = async (useDev: boolean, username: string, email: string
} catch (err) {
throw err;
} finally {
// Return connection
await conn.end();
if (conn) {
conn.end();
}
}
};
@@ -219,8 +262,13 @@ export const loginUser = async (useDev: boolean, username: string, email: string
* @param email The email to check
*/
export const checkUsernameAndEmail = async (useDev: boolean, username: string, email: string): Promise<Status> => {
let conn = await PartyPlanerDB.getConnection(useDev);
let conn;
try {
if (useDev) {
conn = await dev_pool.getConnection();
} else {
conn = await prod_pool.getConnection();
}
const usernameQuery = 'SELECT username FROM users WHERE username = ?';
const emailQuery = 'SELECT email FROM users WHERE email = ?';
const usernameRes = await conn.query(usernameQuery, username);
@@ -267,14 +315,21 @@ export const checkUsernameAndEmail = async (useDev: boolean, username: string, e
} catch (err) {
throw err;
} finally {
// Return connection
await conn.end();
if (conn) {
conn.end();
}
}
};
export const checkSession = async (useDev: boolean, userId: string, sessionId: string, sessionKey: string): Promise<boolean> => {
let conn = await PartyPlanerDB.getConnection(useDev);
let conn;
try {
if (useDev) {
conn = await dev_pool.getConnection();
} else {
conn = await prod_pool.getConnection();
}
let rows = await conn.query('SELECT session_key_hash FROM sessions WHERE user_id = ? AND session_id = ?', [userId, sessionId]);
let savedHash = '';
@@ -286,7 +341,8 @@ export const checkSession = async (useDev: boolean, userId: string, sessionId: s
} catch (err) {
throw err;
} finally {
// Return connection
await conn.end();
if (conn) {
conn.end();
}
}
};
@@ -11,59 +11,6 @@ import * as icalgenerator from './icalgenerator/icalgenerator.service';
*/
export const raPlaMiddlewareRouter = express.Router();
/**
* @swagger
* /rapla-middleware:
* get:
* summary: Retrieve the adjusted RaPla .ics file
* description: Downloads the current .ics file from DHBW servers, removes unwanted events and returns the file.
* Required urls can be generated on https://rapla-middleware.p4ddy.com
* tags:
* - rapla-middleware
* responses:
* 200:
* description: The .ics file
* 400:
* description: Wrong parameters, see response body for detailed information
* 500:
* description: A server error occurred. Please try again. If this issue persists, contact the admin.
* parameters:
* - in: query
* name: user
* required: true
* description: The user from RaPla, can be taken directly from the RaPla link
* schema:
* type: string
* example: mueller
* - in: query
* name: file
* required: true
* description: The file from RaPla, can be taken directly from the RaPla link
* schema:
* type: string
* example: TINF19B4
* - in: query
* name: blockers
* required: false
* description: Whether to remove blockers from the .ics file
* schema:
* type: boolean
* example: 1
* - in: query
* name: wahl
* required: false
* description: The chosen elective module which is not to be filtered out
* schema:
* type: integer
* example: 0
* - in: query
* name: pflicht
* required: false
* description: The chosen profile module which is not to be filtered out
* schema:
* type: integer
* example: 2
*/
raPlaMiddlewareRouter.get('/', async (req: Request, res: Response) => {
try {
let user = (req.query.user ?? '').toString();
@@ -86,7 +33,7 @@ raPlaMiddlewareRouter.get('/', async (req: Request, res: Response) => {
res.set({'Content-Disposition': 'attachment; filename=' + file + '.ics'});
res.status(200).send(resultingFile);
} catch (e: any) {
} catch (e) {
let errorGuid = Guid.create().toString();
logger.error('Error handling a request: ' + e.message, {reference: errorGuid});
res.status(500).send({
@@ -153,11 +153,7 @@ export const removeElective = function (ical: iCalFile, chosenElective: string):
{name: 'Kryptographische Verfahren'},
{name: 'Robotik'},
{name: 'Web-Services'},
{name: 'High Performance Computing'},
{name: 'Digitale Audiosignalverarbeitung'},
{name: 'Psychologische Grundlagen für Informatiker'},
{name: 'Erklärbare Künstliche Intelligenz'},
{name: 'Innovation Management'}
{name: 'High Performance Computing'}
];
electiveToRemove.splice(parseInt(chosenElective), 1);
@@ -1,19 +0,0 @@
import * as dotenv from 'dotenv';
const mariadb = require('mariadb');
dotenv.config();
export namespace HighlightMarkerDB {
const pool = mariadb.createPool({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.BETTERZON_DATABASE,
connectionLimit: 5
});
export const getConnection = async () => {
return pool.getConnection();
};
}
@@ -16,7 +16,7 @@ highlightMarkerRouter.use('/addHighlight', addHighlightRouter);
highlightMarkerRouter.get('/', async (req: Request, res: Response) => {
try {
res.status(200).send('Pluto Development Twitch Highlight Marker API Endpoint');
} catch (e: any) {
} catch (e) {
let errorGuid = Guid.create().toString();
logger.error('Error handling a request: ' + e.message, {reference: errorGuid});
res.status(500).send({
@@ -14,7 +14,7 @@ export const addHighlightRouter = express.Router();
addHighlightRouter.get('/', (req: Request, res: Response) => {
try {
res.status(200).send('GET endpoint not defined.');
} catch (e: any) {
} catch (e) {
let errorGuid = Guid.create().toString();
logger.error('Error handling a request: ' + e.message, {reference: errorGuid});
res.status(500).send({
@@ -45,7 +45,7 @@ addHighlightRouter.post('/', (req: Request, res: Response) => {
res.type('application/json');
res.status(200).send({'status': 'success', 'description': ''});
}
} catch (e: any) {
} catch (e) {
let errorGuid = Guid.create().toString();
logger.error('Error handling a request: ' + e.message, {reference: errorGuid});
res.status(500).send({
@@ -1,15 +1,25 @@
import * as dotenv from 'dotenv';
import {HighlightMarkerDB} from '../HighlightMarker.db';
dotenv.config();
const mariadb = require('mariadb');
const pool = mariadb.createPool({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.TWITCH_HIGHLIGHTS_DATABASE,
connectionLimit: 5
});
/**
* Creates a new highlight entry in SQL
* @param req_body The request body
*/
export const createHighlightEntry = async (req_body: any) => {
let conn = await HighlightMarkerDB.getConnection();
let conn;
try {
conn = await pool.getConnection();
const streamers = await conn.query('SELECT streamer_id FROM streamers WHERE username = ?', req_body.streamer);
let streamer_id: number = -1;
@@ -25,7 +35,8 @@ export const createHighlightEntry = async (req_body: any) => {
} catch (err) {
throw err;
} finally {
// Return connection
await conn.end();
if (conn) {
conn.end();
}
}
};
-3
View File
@@ -1,3 +0,0 @@
test('Test template', async () => {
expect(true).toBe(true);
});
+3 -1
View File
@@ -5,6 +5,8 @@
"outDir": "./dist",
"strict": true,
"esModuleInterop": true,
"inlineSourceMap": true
"inlineSourceMap": true,
"experimentalDecorators": true,
"emitDecoratorMetadata": true
}
}
+8
View File
@@ -0,0 +1,8 @@
{
"entryFile": "app.ts",
"noImplicitAdditionalProperties": "throw-on-extras",
"spec": {
"outputDirectory": "public",
"specVersion": 3
}
}