Compare commits

...

27 Commits

Author SHA1 Message Date
Paddy 871a8aa948 Update multiple depedencies
Jenkins Production Deployment
2022-12-24 21:11:16 +01:00
Paddy 8e503a19e0 Update mariadb version
Jenkins Production Deployment
2022-12-24 20:54:09 +01:00
Paddy 0325534d53 Better connection handling
Jenkins Production Deployment
2022-06-26 14:48:00 +02:00
Paddy fc65474930 Fix security issues
Jenkins Production Deployment
2022-06-25 13:26:16 +02:00
Paddy eeace68b7b Fuck npm
Jenkins Production Deployment
2022-06-25 12:41:49 +02:00
Paddy 123684da13 Reformat code 2022-06-25 12:22:43 +02:00
Paddy 137428ffa7 Adding jest unit testing framework and required sonar config 2022-06-25 12:21:48 +02:00
Paddy a9ad5e8f87 Merge remote-tracking branch 'origin/master'
Jenkins Production Deployment
2022-06-24 21:37:58 +02:00
Paddy bde460f5d2 Adding sonar properties file 2022-06-24 21:37:26 +02:00
Paddy 488f502b2d Merge remote-tracking branch 'origin/master'
Jenkins Production Deployment
# Conflicts:
#	src/models/rapla-middleware/icalgenerator/icalgenerator.service.ts
2022-02-25 09:35:35 +01:00
Paddy 8a6b221513 RaPla Middleware: Fixing elective modules for semester 6 2022-02-25 09:34:56 +01:00
Paddy 9c234e6994 Fixing callout to hcaptcha verify page
Jenkins Production Deployment
2022-01-12 21:32:23 +01:00
Paddy 924d16a1a4 Last adjustments for the gym_id problem on backend side
Jenkins Production Deployment
2022-01-11 18:03:47 +01:00
Paddy c84cbd240d Paddy stupid
Jenkins Production Deployment
2022-01-11 17:27:55 +01:00
Paddy 7d76917591 Even more debugging the gym_id
Jenkins Production Deployment
2022-01-11 17:26:17 +01:00
Paddy 1fcf6fbd81 More debugging the gym_id
Jenkins Production Deployment
2022-01-11 17:16:39 +01:00
Paddy bff3d16c98 Hopefully fixing the gym_id stuff
Jenkins Production Deployment
2022-01-11 17:15:10 +01:00
Paddy 578032c8a6 Debugging routes POST
Jenkins Production Deployment
2022-01-11 17:09:22 +01:00
Paddy 561fbf0a75 Debugging routes POST
Jenkins Production Deployment
2022-01-11 17:07:22 +01:00
Paddy ac8de54d95 Adjusting hcaptcha http parameter name
Jenkins Production Deployment
2022-01-09 21:53:24 +01:00
Paddy 9aebd12d16 Adding documentation for the rest of crr/
Jenkins Production Deployment
2022-01-09 20:32:44 +01:00
Paddy 6f7069fdcb Adding documentation for crr/gyms
Jenkins Production Deployment
2022-01-09 18:44:44 +01:00
Paddy ac29860075 API-35: Swagger documentation (!17)
Jenkins Production Deployment
Co-authored-by: Patrick Mueller <patrick@mueller-patrick.tech>
Reviewed-on: #17
Co-authored-by: Patrick Müller <patrick@plutodev.de>
Co-committed-by: Patrick Müller <patrick@plutodev.de>
2022-01-09 15:19:49 +00:00
Paddy af8f77a268 CRR: Removing console.log
Jenkins Production Deployment
2022-01-09 15:16:31 +01:00
Paddy e98d1d48ab CRR: Fixing captcha http parameter
Jenkins Production Deployment
2022-01-09 15:12:34 +01:00
Paddy 25a66b060c API-37: Adding endpoints for climbing route rating app (!16)
Jenkins Production Deployment
Co-authored-by: Patrick Mueller <patrick@mueller-patrick.tech>
Reviewed-on: #16
Co-authored-by: Patrick Müller <patrick@plutodev.de>
Co-committed-by: Patrick Müller <patrick@plutodev.de>
2022-01-08 22:21:19 +00:00
Paddy b4d5bdd0b6 API-36: 🚑 Fixing critical issue with the amount of sql connections (!15)
Jenkins Production Deployment
Co-authored-by: Patrick Mueller <patrick@mueller-patrick.tech>
Reviewed-on: #15
Co-authored-by: Patrick Müller <patrick@plutodev.de>
Co-committed-by: Patrick Müller <patrick@plutodev.de>
2022-01-08 15:42:09 +00:00
102 changed files with 16099 additions and 4704 deletions
+8
View File
@@ -2,3 +2,11 @@
.idea .idea
**/*.iml **/*.iml
.env .env
# Build output
dist/
logs/
node_modules/
public/
coverage/
testResults/
+60 -6
View File
@@ -1,6 +1,8 @@
import express from 'express'; import express from 'express';
import * as http from 'http'; import * as http from 'http';
import * as dotenv from 'dotenv'; import * as dotenv from 'dotenv';
import swaggerUi from 'swagger-ui-express';
import swaggerJSDoc from 'swagger-jsdoc';
// Router imports // Router imports
import {partyPlanerRouter} from './src/models/partyplaner/PartyPlaner.router'; import {partyPlanerRouter} from './src/models/partyplaner/PartyPlaner.router';
import {highlightMarkerRouter} from './src/models/twitch-highlight-marker/HighlightMarker.router'; import {highlightMarkerRouter} from './src/models/twitch-highlight-marker/HighlightMarker.router';
@@ -9,14 +11,15 @@ import logger from './src/middleware/logger';
import {dhbwRaPlaChangesRouter} from './src/models/dhbw-rapla-changes/DHBWRaPlaChanges.router'; import {dhbwRaPlaChangesRouter} from './src/models/dhbw-rapla-changes/DHBWRaPlaChanges.router';
import {raPlaMiddlewareRouter} from './src/models/rapla-middleware/RaPlaMiddleware.router'; import {raPlaMiddlewareRouter} from './src/models/rapla-middleware/RaPlaMiddleware.router';
import {betterzonRouter} from './src/models/betterzon/Betterzon.router'; import {betterzonRouter} from './src/models/betterzon/Betterzon.router';
import {crrRouter} from './src/models/climbing-route-rating/ClimbingRouteRating.router';
let cors = require('cors'); let cors = require('cors');
dotenv.config(); dotenv.config();
if (!process.env.PORT) { if (!process.env.PORT) {
logger.error('No port'); logger.error('No port');
process.exit(1); process.exit(1);
} }
const port: number = parseInt(process.env.PORT, 10); const port: number = parseInt(process.env.PORT, 10);
@@ -27,8 +30,58 @@ const server: http.Server = http.createServer(app);
// here we are adding middleware to parse all incoming requests as JSON // here we are adding middleware to parse all incoming requests as JSON
app.use(express.json()); app.use(express.json());
// Use CORS // Configure CORS
app.use(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);
}
}));
// 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)
);
// Add routers // Add routers
app.use('/dhbw-service', dhbwServiceRouter); app.use('/dhbw-service', dhbwServiceRouter);
@@ -37,12 +90,13 @@ app.use('/partyplaner', partyPlanerRouter);
app.use('/raplachanges', dhbwRaPlaChangesRouter); app.use('/raplachanges', dhbwRaPlaChangesRouter);
app.use('/rapla-middleware', raPlaMiddlewareRouter); app.use('/rapla-middleware', raPlaMiddlewareRouter);
app.use('/betterzon', betterzonRouter); app.use('/betterzon', betterzonRouter);
app.use('/crr', crrRouter);
// this is a simple route to make sure everything is working properly // this is a simple route to make sure everything is working properly
app.get('/', (req: express.Request, res: express.Response) => { app.get('/', (req: express.Request, res: express.Response) => {
res.status(200).send('Welcome to the Pluto Development REST API V2!'); res.status(200).send('Welcome to the Pluto Development REST API V2!');
}); });
server.listen(port, () => { server.listen(port, () => {
logger.info('Server listening on Port ' + port); logger.info('Server listening on Port ' + port);
}); });
+8
View File
@@ -0,0 +1,8 @@
/** @type {import('ts-jest/dist/types').InitialOptionsTsJest} */
module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
roots: [
'test'
]
};
+11986 -1444
View File
File diff suppressed because it is too large Load Diff
+53 -34
View File
@@ -1,36 +1,55 @@
{ {
"name": "PlutoDevExpressAPI", "name": "plutodev_express_api",
"version": "1.0.0", "version": "1.0.0",
"description": "", "description": "",
"main": "index.js", "main": "index.js",
"scripts": { "scripts": {
"start": "tsc && node ./dist/app.js", "start": "tsc && node ./dist/app.js",
"build": "tsc", "build": "tsc",
"debug": "export DEBUG=* && npm run start", "debug": "export DEBUG=* && npm run start",
"test": "echo \"Error: no test specified\" && exit 1" "test": "jest --coverage --testResultsProcessor ./node_modules/jest-sonar-reporter/index.js"
}, },
"keywords": [], "keywords": [],
"author": "", "author": "",
"license": "ISC", "license": "ISC",
"dependencies": { "dependencies": {
"app-root-path": "^3.0.0", "app-root-path": "^3.0.0",
"bcrypt": "^5.0.1", "axios": "^0.24.0",
"cors": "^2.8.5", "bcrypt": "^5.0.1",
"debug": "^4.3.1", "cors": "^2.8.5",
"dotenv": "^8.2.0", "debug": "^4.3.1",
"express": "^4.17.1", "dotenv": "^8.2.0",
"guid-typescript": "^1.0.9", "express": "^4.18.2",
"mariadb": "^2.5.3", "guid-typescript": "^1.0.9",
"winston": "^3.3.3" "mariadb": "^3.0.2",
}, "random-words": "^1.1.1",
"devDependencies": { "swagger-jsdoc": "^6.1.0",
"@types/app-root-path": "^1.2.4", "swagger-ui-express": "^4.3.0",
"@types/bcrypt": "^3.0.1", "winston": "^3.3.3"
"@types/debug": "^4.1.5", },
"@types/express": "^4.17.11", "devDependencies": {
"@types/winston": "^2.4.4", "@types/app-root-path": "^1.2.4",
"source-map-support": "^0.5.19", "@types/bcrypt": "^3.0.1",
"tslint": "^6.1.3", "@types/debug": "^4.1.5",
"typescript": "^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/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
}
} }
+6
View File
@@ -0,0 +1,6 @@
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
@@ -0,0 +1,19 @@
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();
};
}
+11 -11
View File
@@ -33,15 +33,15 @@ betterzonRouter.use('/crawlingstatus', crawlingstatusRouter);
betterzonRouter.get('/', async (req: Request, res: Response) => { betterzonRouter.get('/', async (req: Request, res: Response) => {
try { try {
res.status(200).send('Pluto Development PartyPlaner API Endpoint V2'); res.status(200).send('Pluto Development Betterzon API Endpoint');
} catch (e) { } catch (e: any) {
let errorGuid = Guid.create().toString(); let errorGuid = Guid.create().toString();
logger.error('Error handling a request: ' + e.message, {reference: errorGuid}); logger.error('Error handling a request: ' + e.message, {reference: errorGuid});
res.status(500).send({ res.status(500).send({
'status': 'PROCESSING_ERROR', 'status': 'PROCESSING_ERROR',
'message': 'Internal Server Error. Try again later.', 'message': 'Internal Server Error. Try again later.',
'reference': errorGuid 'reference': errorGuid
}); });
} }
}); });
@@ -1,5 +1,5 @@
import {Category} from './category.interface'; import {Category} from './category.interface';
export interface Categories { export interface Categories {
[key: number]: Category; [key: number]: Category;
} }
@@ -21,50 +21,50 @@ export const categoriesRouter = express.Router();
// GET categories/ // GET categories/
categoriesRouter.get('/', async (req: Request, res: Response) => { categoriesRouter.get('/', async (req: Request, res: Response) => {
try { try {
const categories: Categories = await CategoryService.findAll(); const categories: Categories = await CategoryService.findAll();
res.status(200).send(categories); res.status(200).send(categories);
} catch (e) { } catch (e: any) {
console.log('Error handling a request: ' + e.message); console.log('Error handling a request: ' + e.message);
res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'})); res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'}));
} }
}); });
// GET categories/:id // GET categories/:id
categoriesRouter.get('/:id', async (req: Request, res: Response) => { categoriesRouter.get('/:id', async (req: Request, res: Response) => {
const id: number = parseInt(req.params.id, 10); const id: number = parseInt(req.params.id, 10);
if (!id) { if (!id) {
res.status(400).send('Missing parameters.'); res.status(400).send('Missing parameters.');
return; return;
} }
try { try {
const category: Category = await CategoryService.find(id); const category: Category = await CategoryService.find(id);
res.status(200).send(category); res.status(200).send(category);
} catch (e) { } catch (e: any) {
console.log('Error handling a request: ' + e.message); console.log('Error handling a request: ' + e.message);
res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'})); res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'}));
} }
}); });
// GET categories/search/:term // GET categories/search/:term
categoriesRouter.get('/search/:term', async (req: Request, res: Response) => { categoriesRouter.get('/search/:term', async (req: Request, res: Response) => {
const term: string = req.params.term; const term: string = req.params.term;
if (!term) { if (!term) {
res.status(400).send('Missing parameters.'); res.status(400).send('Missing parameters.');
return; return;
} }
try { try {
const categories: Categories = await CategoryService.findBySearchTerm(term); const categories: Categories = await CategoryService.findBySearchTerm(term);
res.status(200).send(categories); res.status(200).send(categories);
} catch (e) { } catch (e: any) {
console.log('Error handling a request: ' + e.message); console.log('Error handling a request: ' + e.message);
res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'})); res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'}));
} }
}); });
@@ -1,18 +1,10 @@
import * as dotenv from 'dotenv'; import * as dotenv from 'dotenv';
import {Category} from './category.interface'; import {Category} from './category.interface';
import {Categories} from './categories.interface'; import {Categories} from './categories.interface';
import {BetterzonDB} from '../Betterzon.db';
dotenv.config(); 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 * Data Model Interfaces
*/ */
@@ -26,34 +18,32 @@ const pool = mariadb.createPool({
* Fetches and returns all known categories * Fetches and returns all known categories
*/ */
export const findAll = async (): Promise<Categories> => { export const findAll = async (): Promise<Categories> => {
let conn; let conn = await BetterzonDB.getConnection();
let categRows = []; let categRows = [];
try { try {
conn = await pool.getConnection(); const rows = await conn.query('SELECT category_id, name FROM categories');
const rows = await conn.query('SELECT category_id, name FROM categories'); for (let row in rows) {
for (let row in rows) { if (row !== 'meta') {
if (row !== 'meta') { let categ: Category = {
let categ: Category = { category_id: 0,
category_id: 0, name: ''
name: '' };
}; const sqlCateg = rows[row];
const sqlCateg = rows[row];
categ.category_id = sqlCateg.category_id; categ.category_id = sqlCateg.category_id;
categ.name = sqlCateg.name; categ.name = sqlCateg.name;
categRows.push(categ); categRows.push(categ);
} }
} }
} catch (err) { } catch (err) {
throw err; throw err;
} finally { } finally {
if (conn) { // Return connection
conn.end(); await conn.end();
} }
}
return categRows; return categRows;
}; };
/** /**
@@ -61,26 +51,24 @@ export const findAll = async (): Promise<Categories> => {
* @param id The id of the category to fetch * @param id The id of the category to fetch
*/ */
export const find = async (id: number): Promise<Category> => { export const find = async (id: number): Promise<Category> => {
let conn; let conn = await BetterzonDB.getConnection();
let categ: any; let categ: any;
try { try {
conn = await pool.getConnection(); const rows = await conn.query('SELECT category_id, name FROM categories WHERE category_id = ?', id);
const rows = await conn.query('SELECT category_id, name FROM categories WHERE category_id = ?', id); for (let row in rows) {
for (let row in rows) { if (row !== 'meta') {
if (row !== 'meta') { categ = rows[row];
categ = rows[row]; }
} }
}
} catch (err) { } catch (err) {
throw err; throw err;
} finally { } finally {
if (conn) { // Return connection
conn.end(); await conn.end();
} }
}
return categ; return categ;
}; };
/** /**
@@ -88,25 +76,23 @@ export const find = async (id: number): Promise<Category> => {
* @param term the term to match * @param term the term to match
*/ */
export const findBySearchTerm = async (term: string): Promise<Categories> => { export const findBySearchTerm = async (term: string): Promise<Categories> => {
let conn; let conn = await BetterzonDB.getConnection();
let categRows = []; let categRows = [];
try { try {
conn = await pool.getConnection(); term = '%' + term + '%';
term = '%' + term + '%'; const rows = await conn.query('SELECT category_id, name FROM categories WHERE name LIKE ?', term);
const rows = await conn.query('SELECT category_id, name FROM categories WHERE name LIKE ?', term); for (let row in rows) {
for (let row in rows) { if (row !== 'meta') {
if (row !== 'meta') { categRows.push(rows[row]);
categRows.push(rows[row]); }
} }
}
} catch (err) { } catch (err) {
throw err; throw err;
} finally { } finally {
if (conn) { // Return connection
conn.end(); await conn.end();
} }
}
return categRows; return categRows;
}; };
@@ -1,4 +1,4 @@
export interface Category { export interface Category {
category_id: number; category_id: number;
name: string; name: string;
} }
@@ -1,9 +1,9 @@
export interface Contact_Person { export interface Contact_Person {
contact_person_id: number; contact_person_id: number;
first_name: string; first_name: string;
last_name: string; last_name: string;
gender: string; gender: string;
email: string; email: string;
phone: string; phone: string;
vendor_id: number; vendor_id: number;
} }
@@ -1,5 +1,5 @@
import {Contact_Person} from './contact_person.interface'; import {Contact_Person} from './contact_person.interface';
export interface Contact_Persons { export interface Contact_Persons {
[key: number]: Contact_Person; [key: number]: Contact_Person;
} }
@@ -7,7 +7,6 @@ import * as ContactPersonService from './contact_persons.service';
import {Contact_Person} from './contact_person.interface'; import {Contact_Person} from './contact_person.interface';
import {Contact_Persons} from './contact_persons.interface'; import {Contact_Persons} from './contact_persons.interface';
import * as UserService from '../users/users.service'; import * as UserService from '../users/users.service';
import * as PriceService from '../prices/prices.service';
/** /**
@@ -23,111 +22,111 @@ export const contactpersonsRouter = express.Router();
// GET contactpersons/ // GET contactpersons/
contactpersonsRouter.get('/', async (req: Request, res: Response) => { contactpersonsRouter.get('/', async (req: Request, res: Response) => {
try { try {
const contacts: Contact_Persons = await ContactPersonService.findAll(); const contacts: Contact_Persons = await ContactPersonService.findAll();
res.status(200).send(contacts); res.status(200).send(contacts);
} catch (e) { } catch (e: any) {
console.log('Error handling a request: ' + e.message); console.log('Error handling a request: ' + e.message);
res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'})); res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'}));
} }
}); });
// GET contactpersons/:id // GET contactpersons/:id
contactpersonsRouter.get('/:id', async (req: Request, res: Response) => { contactpersonsRouter.get('/:id', async (req: Request, res: Response) => {
const id: number = parseInt(req.params.id, 10); const id: number = parseInt(req.params.id, 10);
if (!id) { if (!id) {
res.status(400).send('Missing parameters.'); res.status(400).send('Missing parameters.');
return; return;
} }
try { try {
const contact: Contact_Person = await ContactPersonService.find(id); const contact: Contact_Person = await ContactPersonService.find(id);
res.status(200).send(contact); res.status(200).send(contact);
} catch (e) { } catch (e: any) {
console.log('Error handling a request: ' + e.message); console.log('Error handling a request: ' + e.message);
res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'})); res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'}));
} }
}); });
// GET contactpersons/byvendor/:id // GET contactpersons/byvendor/:id
contactpersonsRouter.get('/byvendor/:id', async (req: Request, res: Response) => { contactpersonsRouter.get('/byvendor/:id', async (req: Request, res: Response) => {
const id: number = parseInt(req.params.id, 10); const id: number = parseInt(req.params.id, 10);
if (!id) { if (!id) {
res.status(400).send('Missing parameters.'); res.status(400).send('Missing parameters.');
return; return;
} }
try { try {
const contacts: Contact_Persons = await ContactPersonService.findByVendor(id); const contacts: Contact_Persons = await ContactPersonService.findByVendor(id);
res.status(200).send(contacts); res.status(200).send(contacts);
} catch (e) { } catch (e: any) {
console.log('Error handling a request: ' + e.message); console.log('Error handling a request: ' + e.message);
res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'})); res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'}));
} }
}); });
// POST contactpersons/ // POST contactpersons/
contactpersonsRouter.post('/', async (req: Request, res: Response) => { contactpersonsRouter.post('/', async (req: Request, res: Response) => {
try { try {
// Authenticate user // Authenticate user
const user_ip = req.connection.remoteAddress ?? ''; const user_ip = req.connection.remoteAddress ?? '';
const session_id = req.body.session_id; const session_id = req.body.session_id;
const session_key = req.body.session_key; const session_key = req.body.session_key;
const user = await UserService.checkSession(session_id, session_key, user_ip); const user = await UserService.checkSession(session_id, session_key, user_ip);
// Get required parameters // Get required parameters
const vendor_id = req.body.vendor_id; const vendor_id = req.body.vendor_id;
const first_name = req.body.first_name; const first_name = req.body.first_name;
const last_name = req.body.last_name; const last_name = req.body.last_name;
const gender = req.body.gender; const gender = req.body.gender;
const email = req.body.email; const email = req.body.email;
const phone = req.body.phone; const phone = req.body.phone;
const success = await ContactPersonService.createContactEntry(user.user_id, vendor_id, first_name, last_name, gender, email, phone); const success = await ContactPersonService.createContactEntry(user.user_id, vendor_id, first_name, last_name, gender, email, phone);
if (success) { if (success) {
res.status(201).send({}); res.status(201).send({});
} else { } else {
res.status(500).send({}); res.status(500).send({});
} }
} catch (e) { } catch (e: any) {
console.log('Error handling a request: ' + e.message); console.log('Error handling a request: ' + e.message);
res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'})); res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'}));
} }
}); });
// PUT contactpersons/:id // PUT contactpersons/:id
contactpersonsRouter.put('/:id', async (req: Request, res: Response) => { contactpersonsRouter.put('/:id', async (req: Request, res: Response) => {
try { try {
// Authenticate user // Authenticate user
const user_ip = req.connection.remoteAddress ?? ''; const user_ip = req.connection.remoteAddress ?? '';
const session_id = req.body.session_id; const session_id = req.body.session_id;
const session_key = req.body.session_key; const session_key = req.body.session_key;
const user = await UserService.checkSession(session_id, session_key, user_ip); const user = await UserService.checkSession(session_id, session_key, user_ip);
// Get required parameters // Get required parameters
const contact_person_id = parseInt(req.params.id, 10); const contact_person_id = parseInt(req.params.id, 10);
const vendor_id = req.body.vendor_id; const vendor_id = req.body.vendor_id;
const first_name = req.body.first_name; const first_name = req.body.first_name;
const last_name = req.body.last_name; const last_name = req.body.last_name;
const gender = req.body.gender; const gender = req.body.gender;
const email = req.body.email; const email = req.body.email;
const phone = req.body.phone; const phone = req.body.phone;
const success = await ContactPersonService.updateContactEntry(user.user_id, contact_person_id, vendor_id, first_name, last_name, gender, email, phone); const success = await ContactPersonService.updateContactEntry(user.user_id, contact_person_id, vendor_id, first_name, last_name, gender, email, phone);
if (success) { if (success) {
res.status(200).send({}); res.status(200).send({});
} else { } else {
res.status(500).send({}); res.status(500).send({});
} }
} catch (e) { } catch (e: any) {
console.log('Error handling a request: ' + e.message); console.log('Error handling a request: ' + e.message);
res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'})); res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'}));
} }
}); });
@@ -1,18 +1,10 @@
import * as dotenv from 'dotenv'; import * as dotenv from 'dotenv';
import {Contact_Person} from './contact_person.interface'; import {Contact_Person} from './contact_person.interface';
import {Contact_Persons} from './contact_persons.interface'; import {Contact_Persons} from './contact_persons.interface';
import {BetterzonDB} from '../Betterzon.db';
dotenv.config(); 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 * Data Model Interfaces
*/ */
@@ -26,26 +18,24 @@ const pool = mariadb.createPool({
* Fetches and returns all known contact persons * Fetches and returns all known contact persons
*/ */
export const findAll = async (): Promise<Contact_Persons> => { export const findAll = async (): Promise<Contact_Persons> => {
let conn; let conn = await BetterzonDB.getConnection();
let contRows = []; let contRows = [];
try { 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');
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) {
for (let row in rows) { if (row !== 'meta') {
if (row !== 'meta') { contRows.push(rows[row]);
contRows.push(rows[row]); }
} }
}
} catch (err) { } catch (err) {
throw err; throw err;
} finally { } finally {
if (conn) { // Return connection
conn.end(); await conn.end();
} }
}
return contRows; return contRows;
}; };
/** /**
@@ -53,26 +43,24 @@ export const findAll = async (): Promise<Contact_Persons> => {
* @param id The id of the contact person to fetch * @param id The id of the contact person to fetch
*/ */
export const find = async (id: number): Promise<Contact_Person> => { export const find = async (id: number): Promise<Contact_Person> => {
let conn; let conn = await BetterzonDB.getConnection();
let cont: any; let cont: any;
try { 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);
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) {
for (let row in rows) { if (row !== 'meta') {
if (row !== 'meta') { cont = rows[row];
cont = rows[row]; }
} }
}
} catch (err) { } catch (err) {
throw err; throw err;
} finally { } finally {
if (conn) { // Return connection
conn.end(); await conn.end();
} }
}
return cont; return cont;
}; };
/** /**
@@ -80,26 +68,24 @@ export const find = async (id: number): Promise<Contact_Person> => {
* @param id The id of the vendor to fetch contact persons for * @param id The id of the vendor to fetch contact persons for
*/ */
export const findByVendor = async (id: number): Promise<Contact_Persons> => { export const findByVendor = async (id: number): Promise<Contact_Persons> => {
let conn; let conn = await BetterzonDB.getConnection();
let contRows = []; let contRows = [];
try { 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);
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) {
for (let row in rows) { if (row !== 'meta') {
if (row !== 'meta') { contRows.push(rows[row]);
contRows.push(rows[row]); }
} }
}
} catch (err) { } catch (err) {
throw err; throw err;
} finally { } finally {
if (conn) { // Return connection
conn.end(); await conn.end();
} }
}
return contRows; return contRows;
}; };
/** /**
@@ -113,28 +99,25 @@ export const findByVendor = async (id: number): Promise<Contact_Persons> => {
* @param phone The phone number of the contact person * @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> => { 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; let conn = await BetterzonDB.getConnection();
try { 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) {
return false;
}
// Check if the user is authorized to manage the requested vendor // Create contact person entry
const user_vendor_rows = await conn.query('SELECT vendor_id FROM vendors WHERE vendor_id = ? AND admin_id = ?', [vendor_id, user_id]); const res = await conn.query('INSERT INTO contact_persons (first_name, last_name, gender, email, phone, vendor_id) VALUES (?, ?, ?, ?, ?, ?)', [first_name, last_name, gender, email, phone, vendor_id]);
if (user_vendor_rows.length !== 1) {
return false;
}
// Create contact person entry // If there are more / less than 1 affected rows, return false
const res = await conn.query('INSERT INTO contact_persons (first_name, last_name, gender, email, phone, vendor_id) VALUES (?, ?, ?, ?, ?, ?)', [first_name, last_name, gender, email, phone, vendor_id]); return res.affectedRows === 1;
} catch (err) {
// If there are more / less than 1 affected rows, return false throw err;
return res.affectedRows === 1; } finally {
} catch (err) { // Return connection
throw err; await conn.end();
} finally { }
if (conn) {
conn.end();
}
}
}; };
/** /**
@@ -149,26 +132,23 @@ export const createContactEntry = async (user_id: number, vendor_id: number, fir
* @param phone The phone number of the contact person * @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> => { 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; let conn = await BetterzonDB.getConnection();
try { 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) {
return false;
}
// Check if the user is authorized to manage the requested vendor // Create contact person entry
const user_vendor_rows = await conn.query('SELECT vendor_id FROM vendors WHERE vendor_id = ? AND admin_id = ?', [vendor_id, user_id]); const res = await conn.query('UPDATE contact_persons SET first_name = ?, last_name = ?, gender = ?, email = ?, phone = ? WHERE contact_person_id = ? AND vendor_id = ?', [first_name, last_name, gender, email, phone, contact_person_id, vendor_id]);
if (user_vendor_rows.length !== 1) {
return false;
}
// Create contact person entry // If there are more / less than 1 affected rows, return false
const res = await conn.query('UPDATE contact_persons SET first_name = ?, last_name = ?, gender = ?, email = ?, phone = ? WHERE contact_person_id = ? AND vendor_id = ?', [first_name, last_name, gender, email, phone, contact_person_id, vendor_id]); return res.affectedRows === 1;
} catch (err) {
// If there are more / less than 1 affected rows, return false throw err;
return res.affectedRows === 1; } finally {
} catch (err) { // Return connection
throw err; await conn.end();
} finally { }
if (conn) {
conn.end();
}
}
}; };
@@ -1,7 +1,7 @@
export interface Crawling_Status { export interface Crawling_Status {
process_id: number; process_id: number;
started_timestamp: Date; started_timestamp: Date;
combinations_to_crawl: number; combinations_to_crawl: number;
successful_crawls: number; successful_crawls: number;
failed_crawls: number; failed_crawls: number;
} }
@@ -5,7 +5,6 @@
import express, {Request, Response} from 'express'; import express, {Request, Response} from 'express';
import * as CrawlingStatusService from './crawling_status.service'; import * as CrawlingStatusService from './crawling_status.service';
import {Crawling_Status} from './crawling_status.interface'; import {Crawling_Status} from './crawling_status.interface';
import {Crawling_Statuses} from './crawling_statuses.interface';
import * as UserService from '../users/users.service'; import * as UserService from '../users/users.service';
@@ -22,23 +21,23 @@ export const crawlingstatusRouter = express.Router();
// GET crawlingstatus/ // GET crawlingstatus/
crawlingstatusRouter.get('/', async (req: Request, res: Response) => { crawlingstatusRouter.get('/', async (req: Request, res: Response) => {
try { try {
// Authenticate user // Authenticate user
const user_ip = req.connection.remoteAddress ?? ''; const user_ip = req.connection.remoteAddress ?? '';
const session_id = (req.query.session_id ?? '').toString(); const session_id = (req.query.session_id ?? '').toString();
const session_key = (req.query.session_key ?? '').toString(); const session_key = (req.query.session_key ?? '').toString();
const user = await UserService.checkSession(session_id, session_key, user_ip); const user = await UserService.checkSession(session_id, session_key, user_ip);
if (!user.is_admin) { if (!user.is_admin) {
res.status(403).send({}); res.status(403).send({});
return; return;
} }
const status: Crawling_Status = await CrawlingStatusService.getCurrent(); const status: Crawling_Status = await CrawlingStatusService.getCurrent();
res.status(200).send(status); res.status(200).send(status);
} catch (e) { } catch (e: any) {
console.log('Error handling a request: ' + e.message); console.log('Error handling a request: ' + e.message);
res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'})); res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'}));
} }
}); });
@@ -1,17 +1,9 @@
import * as dotenv from 'dotenv'; import * as dotenv from 'dotenv';
import {Crawling_Status} from './crawling_status.interface'; import {Crawling_Status} from './crawling_status.interface';
import {BetterzonDB} from '../Betterzon.db';
dotenv.config(); 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 * Data Model Interfaces
*/ */
@@ -25,49 +17,46 @@ const pool = mariadb.createPool({
* Fetches and returns the current crawling status if the issuing user is an admin * Fetches and returns the current crawling status if the issuing user is an admin
*/ */
export const getCurrent = async (): Promise<Crawling_Status> => { export const getCurrent = async (): Promise<Crawling_Status> => {
let conn; let conn = await BetterzonDB.getConnection();
try { try {
conn = await pool.getConnection(); // Get the current crawling process
let process_info = {
process_id: -1,
started_timestamp: new Date(),
combinations_to_crawl: -1
};
const process = await conn.query('SELECT process_id, started_timestamp, combinations_to_crawl FROM crawling_processes ORDER BY started_timestamp DESC LIMIT 1');
for (let row in process) {
if (row !== 'meta') {
process_info = process[row];
}
}
// Get the current crawling process // Get the current status
let process_info = { let total_crawls = 0;
process_id: -1, let successful_crawls = 0;
started_timestamp: new Date(), const rows = await conn.query('SELECT COUNT(status_id) as total, SUM(success) as successful FROM crawling_status WHERE process_id = ?', process_info.process_id);
combinations_to_crawl: -1 for (let row in rows) {
}; if (row !== 'meta') {
const process = await conn.query('SELECT process_id, started_timestamp, combinations_to_crawl FROM crawling_processes ORDER BY started_timestamp DESC LIMIT 1'); total_crawls = rows[row].total;
for (let row in process) { successful_crawls = rows[row].successful;
if (row !== 'meta') { }
process_info = process[row]; }
}
}
// Get the current status const failed_crawls = total_crawls - successful_crawls;
let total_crawls = 0;
let successful_crawls = 0;
const rows = await conn.query('SELECT COUNT(status_id) as total, SUM(success) as successful FROM crawling_status WHERE process_id = ?', process_info.process_id);
for (let row in rows) {
if (row !== 'meta') {
total_crawls = rows[row].total;
successful_crawls = rows[row].successful;
}
}
const failed_crawls = total_crawls - successful_crawls; return {
process_id: process_info.process_id,
started_timestamp: process_info.started_timestamp,
combinations_to_crawl: process_info.combinations_to_crawl,
successful_crawls: successful_crawls,
failed_crawls: failed_crawls
};
return { } catch (err) {
process_id: process_info.process_id, throw err;
started_timestamp: process_info.started_timestamp, } finally {
combinations_to_crawl: process_info.combinations_to_crawl, // Return connection
successful_crawls: successful_crawls, await conn.end();
failed_crawls: failed_crawls }
};
} catch (err) {
throw err;
} finally {
if (conn) {
conn.end();
}
}
}; };
@@ -1,5 +1,5 @@
import {Crawling_Status} from './crawling_status.interface'; import {Crawling_Status} from './crawling_status.interface';
export interface Crawling_Statuses { export interface Crawling_Statuses {
[key: number]: Crawling_Status; [key: number]: Crawling_Status;
} }
@@ -1,5 +1,5 @@
export interface FavoriteShop { export interface FavoriteShop {
favorite_id: number; favorite_id: number;
vendor_id: number; vendor_id: number;
user_id: number; user_id: number;
} }
@@ -1,5 +1,5 @@
import {FavoriteShop} from './favoriteshop.interface'; import {FavoriteShop} from './favoriteshop.interface';
export interface FavoriteShops { export interface FavoriteShops {
[key: number]: FavoriteShop; [key: number]: FavoriteShop;
} }
@@ -4,8 +4,6 @@
import express, {Request, Response} from 'express'; import express, {Request, Response} from 'express';
import * as FavoriteShopsService from './favoriteshops.service'; import * as FavoriteShopsService from './favoriteshops.service';
import {FavoriteShop} from './favoriteshop.interface';
import {FavoriteShops} from './favoriteshops.interface';
import * as UserService from '../users/users.service'; import * as UserService from '../users/users.service';
@@ -21,86 +19,86 @@ export const favoriteshopsRouter = express.Router();
//GET favoriteshops/ //GET favoriteshops/
favoriteshopsRouter.get('/', async (req: Request, res: Response) => { favoriteshopsRouter.get('/', async (req: Request, res: Response) => {
try { try {
// Authenticate user // Authenticate user
const user_ip = req.connection.remoteAddress ?? ''; const user_ip = req.connection.remoteAddress ?? '';
const session_id = (req.query.session_id ?? '').toString(); const session_id = (req.query.session_id ?? '').toString();
const session_key = (req.query.session_key ?? '').toString(); const session_key = (req.query.session_key ?? '').toString();
const user = await UserService.checkSession(session_id, session_key, user_ip); const user = await UserService.checkSession(session_id, session_key, user_ip);
const priceAlarms = await FavoriteShopsService.getFavoriteShops(user.user_id); const priceAlarms = await FavoriteShopsService.getFavoriteShops(user.user_id);
res.status(200).send(priceAlarms); res.status(200).send(priceAlarms);
} catch (e) { } catch (e: any) {
console.log('Error handling a request: ' + e.message); console.log('Error handling a request: ' + e.message);
res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'})); res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'}));
} }
}); });
// POST favoriteshops/ // POST favoriteshops/
favoriteshopsRouter.post('/', async (req: Request, res: Response) => { favoriteshopsRouter.post('/', async (req: Request, res: Response) => {
try { try {
// Authenticate user // Authenticate user
const user_ip = req.connection.remoteAddress ?? ''; const user_ip = req.connection.remoteAddress ?? '';
const session_id = req.body.session_id; const session_id = req.body.session_id;
const session_key = req.body.session_key; const session_key = req.body.session_key;
const user = await UserService.checkSession(session_id, session_key, user_ip); const user = await UserService.checkSession(session_id, session_key, user_ip);
// Get info for price alarm creation // Get info for price alarm creation
const vendor_id = req.body.vendor_id; const vendor_id = req.body.vendor_id;
if (!vendor_id) { if (!vendor_id) {
// Missing // Missing
res.status(400).send(JSON.stringify({message: 'Missing parameters'})); res.status(400).send(JSON.stringify({message: 'Missing parameters'}));
return; return;
} }
// Create price alarm // Create price alarm
const success = await FavoriteShopsService.createFavoriteShop(user.user_id, vendor_id); const success = await FavoriteShopsService.createFavoriteShop(user.user_id, vendor_id);
if (success) { if (success) {
res.status(201).send(JSON.stringify({success: true})); res.status(201).send(JSON.stringify({success: true}));
return; return;
} else { } else {
res.status(500).send(JSON.stringify({success: false})); res.status(500).send(JSON.stringify({success: false}));
return; return;
} }
} catch (e) { } catch (e: any) {
console.log('Error handling a request: ' + e.message); console.log('Error handling a request: ' + e.message);
res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'})); res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'}));
} }
}); });
// DELETE favoriteshops/ // DELETE favoriteshops/
favoriteshopsRouter.delete('/:id', async (req: Request, res: Response) => { favoriteshopsRouter.delete('/:id', async (req: Request, res: Response) => {
try { try {
// Authenticate user // Authenticate user
const user_ip = req.connection.remoteAddress ?? ''; const user_ip = req.connection.remoteAddress ?? '';
const session_id = (req.query.session_id ?? '').toString(); const session_id = (req.query.session_id ?? '').toString();
const session_key = (req.query.session_key ?? '').toString(); const session_key = (req.query.session_key ?? '').toString();
const user = await UserService.checkSession(session_id, session_key, user_ip); const user = await UserService.checkSession(session_id, session_key, user_ip);
// Get info for price alarm creation // Get info for price alarm creation
const favorite_id = parseInt(req.params.id, 10); const favorite_id = parseInt(req.params.id, 10);
if (!favorite_id) { if (!favorite_id) {
// Missing // Missing
res.status(400).send(JSON.stringify({message: 'Missing parameters'})); res.status(400).send(JSON.stringify({message: 'Missing parameters'}));
return; return;
} }
// Create price alarm // Create price alarm
const success = await FavoriteShopsService.deleteFavoriteShop(user.user_id, favorite_id); const success = await FavoriteShopsService.deleteFavoriteShop(user.user_id, favorite_id);
if (success) { if (success) {
res.status(201).send(JSON.stringify({success: true})); res.status(201).send(JSON.stringify({success: true}));
return; return;
} else { } else {
res.status(500).send(JSON.stringify({success: false})); res.status(500).send(JSON.stringify({success: false}));
return; return;
} }
} catch (e) { } catch (e: any) {
console.log('Error handling a request: ' + e.message); console.log('Error handling a request: ' + e.message);
res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'})); res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'}));
} }
}); });
@@ -1,17 +1,9 @@
import * as dotenv from 'dotenv'; import * as dotenv from 'dotenv';
import {FavoriteShops} from './favoriteshops.interface'; import {FavoriteShops} from './favoriteshops.interface';
import {BetterzonDB} from '../Betterzon.db';
dotenv.config(); 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 * Data Model Interfaces
*/ */
@@ -27,19 +19,17 @@ const pool = mariadb.createPool({
* @param vendor_id The id of the vendor to set as favorite * @param vendor_id The id of the vendor to set as favorite
*/ */
export const createFavoriteShop = async (user_id: number, vendor_id: number): Promise<boolean> => { export const createFavoriteShop = async (user_id: number, vendor_id: number): Promise<boolean> => {
let conn; let conn = await BetterzonDB.getConnection();
try { try {
conn = await pool.getConnection(); const res = await conn.query('INSERT INTO favorite_shops (vendor_id, user_id) VALUES (?, ?)', [vendor_id, user_id]);
const res = await conn.query('INSERT INTO favorite_shops (vendor_id, user_id) VALUES (?, ?)', [vendor_id, user_id]);
return res.affectedRows === 1; return res.affectedRows === 1;
} catch (err) { } catch (err) {
throw err; throw err;
} finally { } finally {
if (conn) { // Return connection
conn.end(); await conn.end();
} }
}
}; };
/** /**
@@ -47,25 +37,23 @@ export const createFavoriteShop = async (user_id: number, vendor_id: number): Pr
* @param user_id * @param user_id
*/ */
export const getFavoriteShops = async (user_id: number): Promise<FavoriteShops> => { export const getFavoriteShops = async (user_id: number): Promise<FavoriteShops> => {
let conn; let conn = await BetterzonDB.getConnection();
let shops = []; let shops = [];
try { 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);
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) {
for (let row in rows) { if (row !== 'meta') {
if (row !== 'meta') { shops.push(rows[row]);
shops.push(rows[row]); }
} }
}
return shops; return shops;
} catch (err) { } catch (err) {
throw err; throw err;
} finally { } finally {
if (conn) { // Return connection
conn.end(); await conn.end();
} }
}
}; };
/** /**
@@ -74,17 +62,15 @@ export const getFavoriteShops = async (user_id: number): Promise<FavoriteShops>
* @param favorite_id The favorite shop to delete * @param favorite_id The favorite shop to delete
*/ */
export const deleteFavoriteShop = async (user_id: number, favorite_id: number): Promise<boolean> => { export const deleteFavoriteShop = async (user_id: number, favorite_id: number): Promise<boolean> => {
let conn; let conn = await BetterzonDB.getConnection();
try { try {
conn = await pool.getConnection(); const res = await conn.query('DELETE FROM favorite_shops WHERE favorite_id = ? AND user_id = ?', [favorite_id, user_id]);
const res = await conn.query('DELETE FROM favorite_shops WHERE favorite_id = ? AND user_id = ?', [favorite_id, user_id]);
return res.affectedRows === 1; return res.affectedRows === 1;
} catch (err) { } catch (err) {
throw err; throw err;
} finally { } finally {
if (conn) { // Return connection
conn.end(); await conn.end();
} }
}
}; };
@@ -1,4 +1,4 @@
export interface Manufacturer { export interface Manufacturer {
manufacturer_id: number; manufacturer_id: number;
name: string; name: string;
} }
@@ -1,5 +1,5 @@
import {Manufacturer} from './manufacturer.interface'; import {Manufacturer} from './manufacturer.interface';
export interface Manufacturers { export interface Manufacturers {
[key: number]: Manufacturer; [key: number]: Manufacturer;
} }
@@ -21,50 +21,50 @@ export const manufacturersRouter = express.Router();
// GET manufacturers/ // GET manufacturers/
manufacturersRouter.get('/', async (req: Request, res: Response) => { manufacturersRouter.get('/', async (req: Request, res: Response) => {
try { try {
const manufacturers: Manufacturers = await ManufacturerService.findAll(); const manufacturers: Manufacturers = await ManufacturerService.findAll();
res.status(200).send(manufacturers); res.status(200).send(manufacturers);
} catch (e) { } catch (e: any) {
console.log('Error handling a request: ' + e.message); console.log('Error handling a request: ' + e.message);
res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'})); res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'}));
} }
}); });
// GET manufacturers/:id // GET manufacturers/:id
manufacturersRouter.get('/:id', async (req: Request, res: Response) => { manufacturersRouter.get('/:id', async (req: Request, res: Response) => {
const id: number = parseInt(req.params.id, 10); const id: number = parseInt(req.params.id, 10);
if (!id) { if (!id) {
res.status(400).send('Missing parameters.'); res.status(400).send('Missing parameters.');
return; return;
} }
try { try {
const manufacturer: Manufacturer = await ManufacturerService.find(id); const manufacturer: Manufacturer = await ManufacturerService.find(id);
res.status(200).send(manufacturer); res.status(200).send(manufacturer);
} catch (e) { } catch (e: any) {
console.log('Error handling a request: ' + e.message); console.log('Error handling a request: ' + e.message);
res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'})); res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'}));
} }
}); });
// GET manufacturers/:term // GET manufacturers/:term
manufacturersRouter.get('/search/:term', async (req: Request, res: Response) => { manufacturersRouter.get('/search/:term', async (req: Request, res: Response) => {
const term: string = req.params.term; const term: string = req.params.term;
if (!term) { if (!term) {
res.status(400).send('Missing parameters.'); res.status(400).send('Missing parameters.');
return; return;
} }
try { try {
const manufacturer: Manufacturers = await ManufacturerService.findBySearchTerm(term); const manufacturer: Manufacturers = await ManufacturerService.findBySearchTerm(term);
res.status(200).send(manufacturer); res.status(200).send(manufacturer);
} catch (e) { } catch (e: any) {
console.log('Error handling a request: ' + e.message); console.log('Error handling a request: ' + e.message);
res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'})); res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'}));
} }
}); });
@@ -1,18 +1,10 @@
import * as dotenv from 'dotenv'; import * as dotenv from 'dotenv';
import {Manufacturer} from './manufacturer.interface'; import {Manufacturer} from './manufacturer.interface';
import {Manufacturers} from './manufacturers.interface'; import {Manufacturers} from './manufacturers.interface';
import {BetterzonDB} from '../Betterzon.db';
dotenv.config(); 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 * Data Model Interfaces
*/ */
@@ -26,34 +18,32 @@ const pool = mariadb.createPool({
* Fetches and returns all known manufacturers * Fetches and returns all known manufacturers
*/ */
export const findAll = async (): Promise<Manufacturers> => { export const findAll = async (): Promise<Manufacturers> => {
let conn; let conn = await BetterzonDB.getConnection();
let manRows = []; let manRows = [];
try { try {
conn = await pool.getConnection(); const rows = await conn.query('SELECT manufacturer_id, name FROM manufacturers');
const rows = await conn.query('SELECT manufacturer_id, name FROM manufacturers'); for (let row in rows) {
for (let row in rows) { if (row !== 'meta') {
if (row !== 'meta') { let man: Manufacturer = {
let man: Manufacturer = { manufacturer_id: 0,
manufacturer_id: 0, name: ''
name: '' };
}; const sqlMan = rows[row];
const sqlMan = rows[row];
man.manufacturer_id = sqlMan.manufacturer_id; man.manufacturer_id = sqlMan.manufacturer_id;
man.name = sqlMan.name; man.name = sqlMan.name;
manRows.push(man); manRows.push(man);
} }
} }
} catch (err) { } catch (err) {
throw err; throw err;
} finally { } finally {
if (conn) { // Return connection
conn.end(); await conn.end();
} }
}
return manRows; return manRows;
}; };
/** /**
@@ -61,26 +51,24 @@ export const findAll = async (): Promise<Manufacturers> => {
* @param id The id of the manufacturer to fetch * @param id The id of the manufacturer to fetch
*/ */
export const find = async (id: number): Promise<Manufacturer> => { export const find = async (id: number): Promise<Manufacturer> => {
let conn; let conn = await BetterzonDB.getConnection();
let man: any; let man: any;
try { try {
conn = await pool.getConnection(); const rows = await conn.query('SELECT manufacturer_id, name FROM manufacturers WHERE manufacturer_id = ?', id);
const rows = await conn.query('SELECT manufacturer_id, name FROM manufacturers WHERE manufacturer_id = ?', id); for (let row in rows) {
for (let row in rows) { if (row !== 'meta') {
if (row !== 'meta') { man = rows[row];
man = rows[row]; }
} }
}
} catch (err) { } catch (err) {
throw err; throw err;
} finally { } finally {
if (conn) { // Return connection
conn.end(); await conn.end();
} }
}
return man; return man;
}; };
/** /**
@@ -88,25 +76,23 @@ export const find = async (id: number): Promise<Manufacturer> => {
* @param term the term to match * @param term the term to match
*/ */
export const findBySearchTerm = async (term: string): Promise<Manufacturers> => { export const findBySearchTerm = async (term: string): Promise<Manufacturers> => {
let conn; let conn = await BetterzonDB.getConnection();
let manRows = []; let manRows = [];
try { try {
conn = await pool.getConnection(); term = '%' + term + '%';
term = '%' + term + '%'; const rows = await conn.query('SELECT manufacturer_id, name FROM manufacturers WHERE name LIKE ?', term);
const rows = await conn.query('SELECT manufacturer_id, name FROM manufacturers WHERE name LIKE ?', term); for (let row in rows) {
for (let row in rows) { if (row !== 'meta') {
if (row !== 'meta') { manRows.push(rows[row]);
manRows.push(rows[row]); }
} }
}
} catch (err) { } catch (err) {
throw err; throw err;
} finally { } finally {
if (conn) { // Return connection
conn.end(); await conn.end();
} }
}
return manRows; return manRows;
}; };
@@ -1,6 +1,6 @@
export interface PriceAlarm { export interface PriceAlarm {
alarm_id: number; alarm_id: number;
user_id: number; user_id: number;
product_id: number; product_id: number;
defined_price: number; defined_price: number;
} }
@@ -1,5 +1,5 @@
import {PriceAlarm} from './pricealarm.interface'; import {PriceAlarm} from './pricealarm.interface';
export interface PriceAlarms { export interface PriceAlarms {
[key: number]: PriceAlarm; [key: number]: PriceAlarm;
} }
@@ -4,8 +4,6 @@
import express, {Request, Response} from 'express'; import express, {Request, Response} from 'express';
import * as PriceAlarmsService from './pricealarms.service'; import * as PriceAlarmsService from './pricealarms.service';
import {PriceAlarm} from './pricealarm.interface';
import {PriceAlarms} from './pricealarms.interface';
import * as UserService from '../users/users.service'; import * as UserService from '../users/users.service';
@@ -21,114 +19,114 @@ export const pricealarmsRouter = express.Router();
//GET pricealarms/ //GET pricealarms/
pricealarmsRouter.get('/', async (req: Request, res: Response) => { pricealarmsRouter.get('/', async (req: Request, res: Response) => {
try { try {
// Authenticate user // Authenticate user
const user_ip = req.connection.remoteAddress ?? ''; const user_ip = req.connection.remoteAddress ?? '';
const session_id = (req.query.session_id ?? '').toString(); const session_id = (req.query.session_id ?? '').toString();
const session_key = (req.query.session_key ?? '').toString(); const session_key = (req.query.session_key ?? '').toString();
const user = await UserService.checkSession(session_id, session_key, user_ip); const user = await UserService.checkSession(session_id, session_key, user_ip);
const priceAlarms = await PriceAlarmsService.getPriceAlarms(user.user_id); const priceAlarms = await PriceAlarmsService.getPriceAlarms(user.user_id);
res.status(200).send(priceAlarms); res.status(200).send(priceAlarms);
} catch (e) { } catch (e: any) {
console.log('Error handling a request: ' + e.message); console.log('Error handling a request: ' + e.message);
res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'})); res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'}));
} }
}); });
// POST pricealarms/ // POST pricealarms/
pricealarmsRouter.post('/', async (req: Request, res: Response) => { pricealarmsRouter.post('/', async (req: Request, res: Response) => {
try { try {
// Authenticate user // Authenticate user
const user_ip = req.connection.remoteAddress ?? ''; const user_ip = req.connection.remoteAddress ?? '';
const session_id = req.body.session_id; const session_id = req.body.session_id;
const session_key = req.body.session_key; const session_key = req.body.session_key;
const user = await UserService.checkSession(session_id, session_key, user_ip); const user = await UserService.checkSession(session_id, session_key, user_ip);
// Get info for price alarm creation // Get info for price alarm creation
const product_id = req.body.product_id; const product_id = req.body.product_id;
const defined_price = req.body.defined_price; const defined_price = req.body.defined_price;
if (!product_id || !defined_price) { if (!product_id || !defined_price) {
// Missing // Missing
res.status(400).send(JSON.stringify({message: 'Missing parameters'})); res.status(400).send(JSON.stringify({message: 'Missing parameters'}));
return; return;
} }
// Create price alarm // Create price alarm
const success = await PriceAlarmsService.createPriceAlarm(user.user_id, product_id, defined_price); const success = await PriceAlarmsService.createPriceAlarm(user.user_id, product_id, defined_price);
if (success) { if (success) {
res.status(201).send(JSON.stringify({success: true})); res.status(201).send(JSON.stringify({success: true}));
return; return;
} else { } else {
res.status(500).send(JSON.stringify({success: false})); res.status(500).send(JSON.stringify({success: false}));
return; return;
} }
} catch (e) { } catch (e: any) {
console.log('Error handling a request: ' + e.message); console.log('Error handling a request: ' + e.message);
res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'})); res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'}));
} }
}); });
// PUT pricealarms/ // PUT pricealarms/
pricealarmsRouter.put('/', async (req: Request, res: Response) => { pricealarmsRouter.put('/', async (req: Request, res: Response) => {
try { try {
// Authenticate user // Authenticate user
const user_ip = req.connection.remoteAddress ?? ''; const user_ip = req.connection.remoteAddress ?? '';
const session_id = req.body.session_id; const session_id = req.body.session_id;
const session_key = req.body.session_key; const session_key = req.body.session_key;
const user = await UserService.checkSession(session_id, session_key, user_ip); const user = await UserService.checkSession(session_id, session_key, user_ip);
// Get info for price alarm creation // Get info for price alarm creation
const alarm_id = req.body.alarm_id; const alarm_id = req.body.alarm_id;
const defined_price = req.body.defined_price; const defined_price = req.body.defined_price;
if (!alarm_id || !defined_price) { if (!alarm_id || !defined_price) {
// Missing // Missing
res.status(400).send(JSON.stringify({message: 'Missing parameters'})); res.status(400).send(JSON.stringify({message: 'Missing parameters'}));
return; return;
} }
// Update price alarm // Update price alarm
const success = await PriceAlarmsService.updatePriceAlarm(alarm_id, user.user_id, defined_price); const success = await PriceAlarmsService.updatePriceAlarm(alarm_id, user.user_id, defined_price);
if (success) { if (success) {
res.status(200).send(JSON.stringify({success: true})); res.status(200).send(JSON.stringify({success: true}));
return; return;
} else { } else {
res.status(500).send(JSON.stringify({success: false})); res.status(500).send(JSON.stringify({success: false}));
return; return;
} }
} catch (e) { } catch (e: any) {
console.log('Error handling a request: ' + e.message); console.log('Error handling a request: ' + e.message);
res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'})); res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'}));
} }
}); });
// DELETE pricealarms/:id // DELETE pricealarms/:id
pricealarmsRouter.delete('/:id', async (req, res) => { pricealarmsRouter.delete('/:id', async (req, res) => {
try { try {
// Authenticate user // Authenticate user
const user_ip = req.connection.remoteAddress ?? ''; const user_ip = req.connection.remoteAddress ?? '';
const session_id = (req.query.session_id ?? '').toString(); const session_id = (req.query.session_id ?? '').toString();
const session_key = (req.query.session_key ?? '').toString(); const session_key = (req.query.session_key ?? '').toString();
const user = await UserService.checkSession(session_id, session_key, user_ip); const user = await UserService.checkSession(session_id, session_key, user_ip);
const id: number = parseInt(req.params.id, 10); const id: number = parseInt(req.params.id, 10);
const success = await PriceAlarmsService.deletePriceAlarm(id, user.user_id); const success = await PriceAlarmsService.deletePriceAlarm(id, user.user_id);
if (success) { if (success) {
res.status(200).send(JSON.stringify({success: true})); res.status(200).send(JSON.stringify({success: true}));
return; return;
} else { } else {
res.status(500).send(JSON.stringify({success: false})); res.status(500).send(JSON.stringify({success: false}));
return; return;
} }
} catch (e) { } catch (e: any) {
console.log('Error handling a request: ' + e.message); console.log('Error handling a request: ' + e.message);
res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'})); res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'}));
} }
}); });
@@ -1,17 +1,9 @@
import * as dotenv from 'dotenv'; import * as dotenv from 'dotenv';
import {PriceAlarms} from './pricealarms.interface'; import {PriceAlarms} from './pricealarms.interface';
import {BetterzonDB} from '../Betterzon.db';
dotenv.config(); 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 * Data Model Interfaces
*/ */
@@ -28,19 +20,17 @@ const pool = mariadb.createPool({
* @param defined_price The defined price for the price alarm * @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> => { export const createPriceAlarm = async (user_id: number, product_id: number, defined_price: number): Promise<boolean> => {
let conn; let conn = await BetterzonDB.getConnection();
try { 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]);
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; return res.affectedRows === 1;
} catch (err) { } catch (err) {
throw err; throw err;
} finally { } finally {
if (conn) { // Return connection
conn.end(); await conn.end();
} }
}
}; };
/** /**
@@ -48,25 +38,23 @@ export const createPriceAlarm = async (user_id: number, product_id: number, defi
* @param user_id * @param user_id
*/ */
export const getPriceAlarms = async (user_id: number): Promise<PriceAlarms> => { export const getPriceAlarms = async (user_id: number): Promise<PriceAlarms> => {
let conn; let conn = await BetterzonDB.getConnection();
let priceAlarms = []; let priceAlarms = [];
try { 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);
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) {
for (let row in rows) { if (row !== 'meta') {
if (row !== 'meta') { priceAlarms.push(rows[row]);
priceAlarms.push(rows[row]); }
} }
}
return priceAlarms; return priceAlarms;
} catch (err) { } catch (err) {
throw err; throw err;
} finally { } finally {
if (conn) { // Return connection
conn.end(); await conn.end();
} }
}
}; };
/** /**
@@ -76,19 +64,17 @@ export const getPriceAlarms = async (user_id: number): Promise<PriceAlarms> => {
* @param defined_price The defined price for the price alarm * @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> => { export const updatePriceAlarm = async (alarm_id: number, user_id: number, defined_price: number): Promise<boolean> => {
let conn; let conn = await BetterzonDB.getConnection();
try { 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]);
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; return res.affectedRows === 1;
} catch (err) { } catch (err) {
throw err; throw err;
} finally { } finally {
if (conn) { // Return connection
conn.end(); await conn.end();
} }
}
}; };
/** /**
@@ -97,17 +83,15 @@ 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 * @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> => { export const deletePriceAlarm = async (alarm_id: number, user_id: number): Promise<boolean> => {
let conn; let conn = await BetterzonDB.getConnection();
try { try {
conn = await pool.getConnection(); const res = await conn.query('DELETE FROM price_alarms WHERE alarm_id = ? AND user_id = ?', [alarm_id, user_id]);
const res = await conn.query('DELETE FROM price_alarms WHERE alarm_id = ? AND user_id = ?', [alarm_id, user_id]);
return res.affectedRows === 1; return res.affectedRows === 1;
} catch (err) { } catch (err) {
throw err; throw err;
} finally { } finally {
if (conn) { // Return connection
conn.end(); await conn.end();
} }
}
}; };
+21 -21
View File
@@ -1,27 +1,27 @@
export interface Price { export interface Price {
price_id: number; price_id: number;
product_id: number; product_id: number;
vendor_id: number; vendor_id: number;
price_in_cents: number; price_in_cents: number;
timestamp: Date; timestamp: Date;
} }
export class Deal implements Price { export class Deal implements Price {
price_id: number; price_id: number;
product_id: number; product_id: number;
vendor_id: number; vendor_id: number;
price_in_cents: number; price_in_cents: number;
timestamp: Date; timestamp: Date;
amazonDifference: number; amazonDifference: number;
amazonDifferencePercent: number; amazonDifferencePercent: number;
constructor(price_id: number, product_id: number, vendor_id: number, price_in_cents: number, timestamp: Date, amazonDifference: number, amazonDifferencePercent: number) { constructor(price_id: number, product_id: number, vendor_id: number, price_in_cents: number, timestamp: Date, amazonDifference: number, amazonDifferencePercent: number) {
this.price_id = price_id; this.price_id = price_id;
this.product_id = product_id; this.product_id = product_id;
this.vendor_id = vendor_id; this.vendor_id = vendor_id;
this.price_in_cents = price_in_cents; this.price_in_cents = price_in_cents;
this.timestamp = timestamp; this.timestamp = timestamp;
this.amazonDifference = amazonDifference; this.amazonDifference = amazonDifference;
this.amazonDifferencePercent = amazonDifferencePercent; this.amazonDifferencePercent = amazonDifferencePercent;
} }
} }
@@ -1,5 +1,5 @@
import {Price} from './price.interface'; import {Price} from './price.interface';
export interface Prices { export interface Prices {
[key: number]: Price; [key: number]: Price;
} }
+75 -75
View File
@@ -22,109 +22,109 @@ export const pricesRouter = express.Router();
// GET prices/ // GET prices/
pricesRouter.get('/', async (req: Request, res: Response) => { pricesRouter.get('/', async (req: Request, res: Response) => {
try { try {
let prices: Prices = []; let prices: Prices = [];
const product = req.query.product; const product = req.query.product;
const vendor = req.query.vendor; const vendor = req.query.vendor;
const type = req.query.type; const type = req.query.type;
if (product) { if (product) {
if (vendor) { if (vendor) {
prices = await PriceService.findByVendor(<string> product, <string> vendor, <string> type); prices = await PriceService.findByVendor(<string>product, <string>vendor, <string>type);
} else { } else {
prices = await PriceService.findByType(<string> product, <string> type); prices = await PriceService.findByType(<string>product, <string>type);
} }
} else { } else {
prices = await PriceService.findAll(); prices = await PriceService.findAll();
} }
res.status(200).send(prices); res.status(200).send(prices);
} catch (e) { } catch (e: any) {
console.log('Error handling a request: ' + e.message); console.log('Error handling a request: ' + e.message);
res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'})); res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'}));
} }
}); });
// GET prices/:id // GET prices/:id
pricesRouter.get('/:id', async (req: Request, res: Response) => { pricesRouter.get('/:id', async (req: Request, res: Response) => {
const id: number = parseInt(req.params.id, 10); const id: number = parseInt(req.params.id, 10);
if (!id) { if (!id) {
res.status(400).send('Missing parameters.'); res.status(400).send('Missing parameters.');
return; return;
} }
try { try {
const price: Price = await PriceService.find(id); const price: Price = await PriceService.find(id);
res.status(200).send(price); res.status(200).send(price);
} catch (e) { } catch (e: any) {
console.log('Error handling a request: ' + e.message); console.log('Error handling a request: ' + e.message);
res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'})); res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'}));
} }
}); });
// GET prices/bestDeals // GET prices/bestDeals
pricesRouter.get('/bestDeals/:amount', async (req: Request, res: Response) => { pricesRouter.get('/bestDeals/:amount', async (req: Request, res: Response) => {
const amount: number = parseInt(req.params.amount, 10); const amount: number = parseInt(req.params.amount, 10);
if (!amount) { if (!amount) {
res.status(400).send('Missing parameters.'); res.status(400).send('Missing parameters.');
return; return;
} }
try { try {
const prices: Prices = await PriceService.getBestDeals(amount); const prices: Prices = await PriceService.getBestDeals(amount);
res.status(200).send(prices); res.status(200).send(prices);
} catch (e) { } catch (e: any) {
console.log('Error handling a request: ' + e.message); console.log('Error handling a request: ' + e.message);
res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'})); res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'}));
} }
}); });
// GET prices/byProduct/list/[] // GET prices/byProduct/list/[]
pricesRouter.get('/byProduct/list/:ids', async (req: Request, res: Response) => { pricesRouter.get('/byProduct/list/:ids', async (req: Request, res: Response) => {
const productIds: [number] = JSON.parse(req.params.ids); const productIds: [number] = JSON.parse(req.params.ids);
if (!productIds) { if (!productIds) {
res.status(400).send('Missing parameters.'); res.status(400).send('Missing parameters.');
return; return;
} }
try { try {
const prices: Prices = await PriceService.findListByProducts(productIds); const prices: Prices = await PriceService.findListByProducts(productIds);
res.status(200).send(prices); res.status(200).send(prices);
} catch (e) { } catch (e: any) {
console.log('Error handling a request: ' + e.message); console.log('Error handling a request: ' + e.message);
res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'})); res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'}));
} }
}); });
// POST prices/ // POST prices/
pricesRouter.post('/', async (req: Request, res: Response) => { pricesRouter.post('/', async (req: Request, res: Response) => {
try { try {
// Authenticate user // Authenticate user
const user_ip = req.connection.remoteAddress ?? ''; const user_ip = req.connection.remoteAddress ?? '';
const session_id = req.body.session_id; const session_id = req.body.session_id;
const session_key = req.body.session_key; const session_key = req.body.session_key;
const user = await UserService.checkSession(session_id, session_key, user_ip); const user = await UserService.checkSession(session_id, session_key, user_ip);
// Get required parameters // Get required parameters
const vendor_id = req.body.vendor_id; const vendor_id = req.body.vendor_id;
const product_id = req.body.product_id; const product_id = req.body.product_id;
const price_in_cents = req.body.price_in_cents; const price_in_cents = req.body.price_in_cents;
const success = await PriceService.createPriceEntry(user.user_id, vendor_id, product_id, price_in_cents); const success = await PriceService.createPriceEntry(user.user_id, vendor_id, product_id, price_in_cents);
if (success) { if (success) {
res.status(201).send({}); res.status(201).send({});
} else { } else {
res.status(500).send({}); res.status(500).send({});
} }
} catch (e) { } catch (e: any) {
console.log('Error handling a request: ' + e.message); console.log('Error handling a request: ' + e.message);
res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'})); res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'}));
} }
}); });
+265 -292
View File
@@ -1,18 +1,10 @@
import * as dotenv from 'dotenv'; import * as dotenv from 'dotenv';
import {Deal, Price} from './price.interface'; import {Deal, Price} from './price.interface';
import {Prices} from './prices.interface'; import {Prices} from './prices.interface';
import {BetterzonDB} from '../Betterzon.db';
dotenv.config(); 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 * Data Model Interfaces
*/ */
@@ -26,40 +18,38 @@ const pool = mariadb.createPool({
* Fetches and returns all known prices * Fetches and returns all known prices
*/ */
export const findAll = async (): Promise<Prices> => { export const findAll = async (): Promise<Prices> => {
let conn; let conn = await BetterzonDB.getConnection();
let priceRows = []; let priceRows = [];
try { 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');
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) {
for (let row in rows) { if (row !== 'meta') {
if (row !== 'meta') { let price: Price = {
let price: Price = { price_id: 0,
price_id: 0, price_in_cents: 0,
price_in_cents: 0, product_id: 0,
product_id: 0, timestamp: new Date(),
timestamp: new Date(), vendor_id: 0
vendor_id: 0 };
}; const sqlPrice = rows[row];
const sqlPrice = rows[row];
price.price_id = sqlPrice.price_id; price.price_id = sqlPrice.price_id;
price.product_id = sqlPrice.product_id; price.product_id = sqlPrice.product_id;
price.vendor_id = sqlPrice.vendor_id; price.vendor_id = sqlPrice.vendor_id;
price.price_in_cents = sqlPrice.price_in_cents; price.price_in_cents = sqlPrice.price_in_cents;
price.timestamp = sqlPrice.timestamp; price.timestamp = sqlPrice.timestamp;
priceRows.push(price); priceRows.push(price);
} }
} }
} catch (err) { } catch (err) {
throw err; throw err;
} finally { } finally {
if (conn) { // Return connection
conn.end(); await conn.end();
} }
}
return priceRows; return priceRows;
}; };
/** /**
@@ -67,26 +57,24 @@ export const findAll = async (): Promise<Prices> => {
* @param id The id of the price to fetch * @param id The id of the price to fetch
*/ */
export const find = async (id: number): Promise<Price> => { export const find = async (id: number): Promise<Price> => {
let conn; let conn = await BetterzonDB.getConnection();
let price: any; let price: any;
try { 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);
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) {
for (let row in rows) { if (row !== 'meta') {
if (row !== 'meta') { price = rows[row];
price = rows[row]; }
} }
}
} catch (err) { } catch (err) {
throw err; throw err;
} finally { } finally {
if (conn) { // Return connection
conn.end(); await conn.end();
} }
}
return price; return price;
}; };
/** /**
@@ -94,26 +82,24 @@ export const find = async (id: number): Promise<Price> => {
* @param product the product to fetch the prices for * @param product the product to fetch the prices for
*/ */
export const findByProduct = async (product: number): Promise<Prices> => { export const findByProduct = async (product: number): Promise<Prices> => {
let conn; let conn = await BetterzonDB.getConnection();
let priceRows = []; let priceRows = [];
try { 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);
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) {
for (let row in rows) { if (row !== 'meta') {
if (row !== 'meta') { priceRows.push(rows[row]);
priceRows.push(rows[row]); }
} }
}
} catch (err) { } catch (err) {
throw err; throw err;
} finally { } finally {
if (conn) { // Return connection
conn.end(); await conn.end();
} }
}
return priceRows; return priceRows;
}; };
/** /**
@@ -125,50 +111,48 @@ export const findByProduct = async (product: number): Promise<Prices> => {
* @param type The type of prices, e.g. newest / lowest * @param type The type of prices, e.g. newest / lowest
*/ */
export const findByType = async (product: string, type: string): Promise<Prices> => { export const findByType = async (product: string, type: string): Promise<Prices> => {
let conn; let conn = await BetterzonDB.getConnection();
let priceRows = []; let priceRows = [];
try { try {
conn = await pool.getConnection(); let rows = [];
let rows = []; if (type === 'newest') {
if (type === 'newest') { // Used to get the newest price for this product per vendor
// Used to get the newest price for this product per vendor rows = await conn.query(('WITH summary AS ( ' +
rows = await conn.query(('WITH summary AS ( ' + 'SELECT p.product_id, ' +
'SELECT p.product_id, ' + 'p.vendor_id, ' +
'p.vendor_id, ' + 'p.price_in_cents, ' +
'p.price_in_cents, ' + 'p.timestamp, ' +
'p.timestamp, ' + 'ROW_NUMBER() OVER( ' +
'ROW_NUMBER() OVER( ' + 'PARTITION BY p.vendor_id ' +
'PARTITION BY p.vendor_id ' + 'ORDER BY p.timestamp DESC) AS rk ' +
'ORDER BY p.timestamp DESC) AS rk ' + 'FROM prices p ' +
'FROM prices p ' + 'LEFT OUTER JOIN vendors v ON v.vendor_id = p.vendor_id ' +
'LEFT OUTER JOIN vendors v ON v.vendor_id = p.vendor_id ' + 'WHERE product_id = ? AND p.vendor_id != 1 AND active_listing = true AND v.isActive = true) ' +
'WHERE product_id = ? AND p.vendor_id != 1 AND active_listing = true AND v.isActive = true) ' + 'SELECT s.* ' +
'SELECT s.* ' + 'FROM summary s ' +
'FROM summary s ' + 'WHERE s.rk = 1 '), product);
'WHERE s.rk = 1 '), product); } else if (type === 'lowest') {
} else if (type === 'lowest') { // Used to get the lowest prices for this product over a period of time
// Used to get the lowest prices for this product over a period of time rows = await conn.query('SELECT price_id, product_id, p.vendor_id, MIN(price_in_cents) as price_in_cents, timestamp FROM prices p LEFT OUTER JOIN vendors v ON v.vendor_id = p.vendor_id WHERE product_id = ? AND v.vendor_id != 1 AND active_listing = true AND v.isActive = true GROUP BY DAY(timestamp) ORDER BY timestamp', product);
rows = await conn.query('SELECT price_id, product_id, p.vendor_id, MIN(price_in_cents) as price_in_cents, timestamp FROM prices p LEFT OUTER JOIN vendors v ON v.vendor_id = p.vendor_id WHERE product_id = ? AND v.vendor_id != 1 AND active_listing = true AND v.isActive = true GROUP BY DAY(timestamp) ORDER BY timestamp', product); } else {
} else { // If no type is given, return all prices for this product
// If no type is given, return all prices for this product 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 p.vendor_id != 1 AND active_listing = true AND v.isActive = true', product);
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 p.vendor_id != 1 AND active_listing = true AND v.isActive = true', product); }
}
for (let row in rows) { for (let row in rows) {
if (row !== 'meta') { if (row !== 'meta') {
priceRows.push(rows[row]); priceRows.push(rows[row]);
} }
} }
} catch (err) { } catch (err) {
throw err; throw err;
} finally { } finally {
if (conn) { // Return connection
conn.end(); await conn.end();
} }
}
return priceRows; return priceRows;
}; };
/** /**
@@ -181,37 +165,35 @@ export const findByType = async (product: string, type: string): Promise<Prices>
* @param type The type of prices, e.g. newest / lowest * @param type The type of prices, e.g. newest / lowest
*/ */
export const findByVendor = async (product: string, vendor: string, type: string): Promise<Prices> => { export const findByVendor = async (product: string, vendor: string, type: string): Promise<Prices> => {
let conn; let conn = await BetterzonDB.getConnection();
let priceRows = []; let priceRows = [];
try { try {
conn = await pool.getConnection(); let rows = [];
let rows = []; if (type === 'newest') {
if (type === 'newest') { // Used to get the newest price for this product and vendor
// Used to get the newest price for this product and vendor 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 p.vendor_id = ? AND active_listing = true AND v.isActive = true ORDER BY timestamp DESC LIMIT 1', [product, vendor]);
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 p.vendor_id = ? AND active_listing = true AND v.isActive = true ORDER BY timestamp DESC LIMIT 1', [product, vendor]); } else if (type === 'lowest') {
} else if (type === 'lowest') { // Used to get the lowest prices for this product and vendor in all time
// Used to get the lowest prices for this product and vendor in all time rows = await conn.query('SELECT price_id, product_id, p.vendor_id, MIN(price_in_cents) as price_in_cents, timestamp FROM prices p LEFT OUTER JOIN vendors v ON v.vendor_id = p.vendor_id WHERE product_id = ? AND p.vendor_id = ? AND active_listing = true AND v.isActive = true LIMIT 1', [product, vendor]);
rows = await conn.query('SELECT price_id, product_id, p.vendor_id, MIN(price_in_cents) as price_in_cents, timestamp FROM prices p LEFT OUTER JOIN vendors v ON v.vendor_id = p.vendor_id WHERE product_id = ? AND p.vendor_id = ? AND active_listing = true AND v.isActive = true LIMIT 1', [product, vendor]); } else {
} else { // If no type is given, return all prices for this product and vendor
// If no type is given, return all prices for this product and vendor 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 p.vendor_id = ? AND active_listing = true AND v.isActive = true', [product, vendor]);
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 p.vendor_id = ? AND active_listing = true AND v.isActive = true', [product, vendor]); }
}
for (let row in rows) { for (let row in rows) {
if (row !== 'meta') { if (row !== 'meta') {
priceRows.push(rows[row]); priceRows.push(rows[row]);
} }
} }
} catch (err) { } catch (err) {
throw err; throw err;
} finally { } finally {
if (conn) { // Return connection
conn.end(); await conn.end();
} }
}
return priceRows; return priceRows;
}; };
/** /**
@@ -220,96 +202,93 @@ export const findByVendor = async (product: string, vendor: string, type: string
* @param amount The amount of deals to return * @param amount The amount of deals to return
*/ */
export const getBestDeals = async (amount: number): Promise<Prices> => { export const getBestDeals = async (amount: number): Promise<Prices> => {
let conn; let conn = await BetterzonDB.getConnection();
let priceRows = []; let priceRows = [];
try { try {
conn = await pool.getConnection(); let allPrices: Record<number, Price[]> = {};
let allPrices: Record<number, Price[]> = {}; // Get newest prices for every product at every vendor
const rows = await conn.query(
'WITH summary AS (\n' +
' SELECT p.product_id,\n' +
' p.vendor_id,\n' +
' p.price_in_cents,\n' +
' p.timestamp,\n' +
' ROW_NUMBER() OVER(\n' +
' PARTITION BY p.product_id, p.vendor_id\n' +
' ORDER BY p.timestamp DESC) AS rk\n' +
' FROM prices p LEFT OUTER JOIN vendors v ON v.vendor_id = p.vendor_id WHERE active_listing = true AND v.isActive = true)\n' +
'SELECT s.*\n' +
'FROM summary s\n' +
'WHERE s.rk = 1');
// Get newest prices for every product at every vendor // Write returned values to allPrices map with product id as key and a list of prices as value
const rows = await conn.query( for (let row in rows) {
'WITH summary AS (\n' + if (row !== 'meta') {
' SELECT p.product_id,\n' + if (!allPrices[parseInt(rows[row].product_id)]) {
' p.vendor_id,\n' + allPrices[parseInt(rows[row].product_id)] = [];
' p.price_in_cents,\n' + }
' p.timestamp,\n' +
' ROW_NUMBER() OVER(\n' +
' PARTITION BY p.product_id, p.vendor_id\n' +
' ORDER BY p.timestamp DESC) AS rk\n' +
' FROM prices p LEFT OUTER JOIN vendors v ON v.vendor_id = p.vendor_id WHERE active_listing = true AND v.isActive = true)\n' +
'SELECT s.*\n' +
'FROM summary s\n' +
'WHERE s.rk = 1');
// Write returned values to allPrices map with product id as key and a list of prices as value allPrices[parseInt(rows[row].product_id)].push(rows[row]);
for (let row in rows) { }
if (row !== 'meta') { }
if (!allPrices[parseInt(rows[row].product_id)]) {
allPrices[parseInt(rows[row].product_id)] = [];
}
allPrices[parseInt(rows[row].product_id)].push(rows[row]); // Iterate over all prices to find the products with the biggest difference between amazon and other vendor
} let deals: Deal[] = [];
}
// Iterate over all prices to find the products with the biggest difference between amazon and other vendor Object.keys(allPrices).forEach(productId => {
let deals: Deal[] = []; if (allPrices[parseInt(productId)]) {
let pricesForProd = allPrices[parseInt(productId)];
Object.keys(allPrices).forEach(productId => { // Get amazon price and lowest price from other vendor
if (allPrices[parseInt(productId)]) { let amazonPrice = {} as Price;
let pricesForProd = allPrices[parseInt(productId)]; let lowestPrice = {} as Price;
pricesForProd.forEach(function (price, priceIndex) {
if (price.vendor_id === 1) {
amazonPrice = price;
} else {
// If there is no lowest price yet or the price of the current iteration is lower, set / replace it
if (!lowestPrice.price_in_cents || lowestPrice.price_in_cents > price.price_in_cents) {
lowestPrice = price;
}
}
});
// Get amazon price and lowest price from other vendor // Create deal object and add it to list
let amazonPrice = {} as Price; let deal = {
let lowestPrice = {} as Price; 'product_id': lowestPrice.product_id,
pricesForProd.forEach(function (price, priceIndex) { 'vendor_id': lowestPrice.vendor_id,
if (price.vendor_id === 1) { 'price_in_cents': lowestPrice.price_in_cents,
amazonPrice = price; 'timestamp': lowestPrice.timestamp,
} else { 'amazonDifference': (amazonPrice.price_in_cents - lowestPrice.price_in_cents),
// If there is no lowest price yet or the price of the current iteration is lower, set / replace it 'amazonDifferencePercent': ((amazonPrice.price_in_cents / lowestPrice.price_in_cents) * 100)
if (!lowestPrice.price_in_cents || lowestPrice.price_in_cents > price.price_in_cents) { };
lowestPrice = price;
}
}
});
// Create deal object and add it to list // Push only deals were the amazon price is actually higher
let deal = { if (deal.amazonDifferencePercent > 0 && deal.amazonDifference > 0) {
'product_id': lowestPrice.product_id, deals.push(deal as Deal);
'vendor_id': lowestPrice.vendor_id, }
'price_in_cents': lowestPrice.price_in_cents, }
'timestamp': lowestPrice.timestamp, });
'amazonDifference': (amazonPrice.price_in_cents - lowestPrice.price_in_cents),
'amazonDifferencePercent': ((amazonPrice.price_in_cents / lowestPrice.price_in_cents) * 100)
};
// Push only deals were the amazon price is actually higher // Sort to have the best deals on the top
if (deal.amazonDifferencePercent > 0 && deal.amazonDifference > 0) { deals.sort((a, b) => a.amazonDifferencePercent! < b.amazonDifferencePercent! ? 1 : -1);
deals.push(deal as Deal);
}
}
});
// Sort to have the best deals on the top // Return only as many records as requested or the maximum amount of found deals, whatever is less
deals.sort((a, b) => a.amazonDifferencePercent! < b.amazonDifferencePercent! ? 1 : -1); let maxAmt = Math.min(amount, deals.length);
// Return only as many records as requested or the maximum amount of found deals, whatever is less for (let dealIndex = 0; dealIndex < maxAmt; dealIndex++) {
let maxAmt = Math.min(amount, deals.length); priceRows.push(deals[dealIndex] as Price);
}
} catch (err) {
console.log(err);
throw err;
} finally {
// Return connection
await conn.end();
}
for (let dealIndex = 0; dealIndex < maxAmt; dealIndex++) { return priceRows;
priceRows.push(deals[dealIndex] as Price);
}
} catch (err) {
console.log(err);
throw err;
} finally {
if (conn) {
conn.end();
}
}
return priceRows;
}; };
/** /**
@@ -317,85 +296,79 @@ export const getBestDeals = async (amount: number): Promise<Prices> => {
* @param productIds the ids of the products * @param productIds the ids of the products
*/ */
export const findListByProducts = async (productIds: [number]): Promise<Prices> => { export const findListByProducts = async (productIds: [number]): Promise<Prices> => {
let conn; let conn = await BetterzonDB.getConnection();
let priceRows: Price[] = []; let priceRows: Price[] = [];
try { try {
conn = await pool.getConnection(); let allPrices: Record<number, Price[]> = {};
let allPrices: Record<number, Price[]> = {}; // Get newest prices for every given product at every vendor
const rows = await conn.query(
'WITH summary AS (\n' +
' SELECT p.product_id,\n' +
' p.vendor_id,\n' +
' p.price_in_cents,\n' +
' p.timestamp,\n' +
' ROW_NUMBER() OVER(\n' +
' PARTITION BY p.product_id, p.vendor_id\n' +
' ORDER BY p.timestamp DESC) AS rk\n' +
' FROM prices p LEFT OUTER JOIN vendors v ON v.vendor_id = p.vendor_id ' +
' WHERE p.product_id IN (?) AND v.isActive = true' +
' AND p.vendor_id != 1 AND active_listing = true)\n' +
'SELECT s.*\n' +
'FROM summary s\n' +
'WHERE s.rk = 1', [productIds]);
// Get newest prices for every given product at every vendor // Write returned values to allPrices map with product id as key and a list of prices as value
const rows = await conn.query( for (let row in rows) {
'WITH summary AS (\n' + if (row !== 'meta') {
' SELECT p.product_id,\n' + if (!allPrices[parseInt(rows[row].product_id)]) {
' p.vendor_id,\n' + allPrices[parseInt(rows[row].product_id)] = [];
' p.price_in_cents,\n' + }
' p.timestamp,\n' +
' ROW_NUMBER() OVER(\n' +
' PARTITION BY p.product_id, p.vendor_id\n' +
' ORDER BY p.timestamp DESC) AS rk\n' +
' FROM prices p LEFT OUTER JOIN vendors v ON v.vendor_id = p.vendor_id ' +
' WHERE p.product_id IN (?) AND v.isActive = true' +
' AND p.vendor_id != 1 AND active_listing = true)\n' +
'SELECT s.*\n' +
'FROM summary s\n' +
'WHERE s.rk = 1', [productIds]);
// Write returned values to allPrices map with product id as key and a list of prices as value allPrices[parseInt(rows[row].product_id)].push(rows[row]);
for (let row in rows) { }
if (row !== 'meta') { }
if (!allPrices[parseInt(rows[row].product_id)]) {
allPrices[parseInt(rows[row].product_id)] = [];
}
allPrices[parseInt(rows[row].product_id)].push(rows[row]); // Iterate over all products to find lowest price
} Object.keys(allPrices).forEach(productId => {
} if (allPrices[parseInt(productId)]) {
let pricesForProd = allPrices[parseInt(productId)];
// Iterate over all products to find lowest price // Sort ascending by price so index 0 has the lowest price
Object.keys(allPrices).forEach(productId => { pricesForProd.sort((a, b) => a.price_in_cents > b.price_in_cents ? 1 : -1);
if (allPrices[parseInt(productId)]) {
let pricesForProd = allPrices[parseInt(productId)];
// Sort ascending by price so index 0 has the lowest price // Push the lowest price to the return list
pricesForProd.sort((a, b) => a.price_in_cents > b.price_in_cents ? 1 : -1); priceRows.push(pricesForProd[0]);
}
});
} catch (err) {
throw err;
} finally {
// Return connection
await conn.end();
}
// Push the lowest price to the return list return priceRows;
priceRows.push(pricesForProd[0]);
}
});
} catch (err) {
throw err;
} finally {
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> => { export const createPriceEntry = async (user_id: number, vendor_id: number, product_id: number, price_in_cents: number): Promise<Boolean> => {
let conn; let conn = await BetterzonDB.getConnection();
try { 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) {
return false;
}
// Check if the user is authorized to manage the requested vendor // Create price entry
const user_vendor_rows = await conn.query('SELECT vendor_id FROM vendors WHERE vendor_id = ? AND admin_id = ?', [vendor_id, user_id]); const res = await conn.query('INSERT INTO prices (product_id, vendor_id, price_in_cents) VALUES (?,?,?)', [product_id, vendor_id, price_in_cents]);
if (user_vendor_rows.length !== 1) {
return false;
}
// Create price entry // If there are more / less than 1 affected rows, return false
const res = await conn.query('INSERT INTO prices (product_id, vendor_id, price_in_cents) VALUES (?,?,?)', [product_id, vendor_id, price_in_cents]); return res.affectedRows === 1;
} catch (err) {
// If there are more / less than 1 affected rows, return false throw err;
return res.affectedRows === 1; } finally {
} catch (err) { // Return connection
throw err; await conn.end();
} finally { }
if (conn) {
conn.end();
}
}
}; };
@@ -1,14 +1,14 @@
export interface Product { export interface Product {
product_id: number; product_id: number;
asin: string; asin: string;
is_active: boolean; is_active: boolean;
name: string; name: string;
short_description: string; short_description: string;
long_description: string; long_description: string;
image_guid: string; image_guid: string;
date_added: Date; date_added: Date;
last_modified: Date; last_modified: Date;
manufacturer_id: number; manufacturer_id: number;
selling_rank: string; selling_rank: string;
category_id: number; category_id: number;
} }
@@ -1,5 +1,5 @@
import {Product} from './product.interface'; import {Product} from './product.interface';
export interface Products { export interface Products {
[key: number]: Product; [key: number]: Product;
} }
@@ -21,111 +21,111 @@ export const productsRouter = express.Router();
// GET products/ // GET products/
productsRouter.get('/', async (req: Request, res: Response) => { productsRouter.get('/', async (req: Request, res: Response) => {
try { try {
const products: Products = await ProductService.findAll(); const products: Products = await ProductService.findAll();
res.status(200).send(products); res.status(200).send(products);
} catch (e) { } catch (e: any) {
console.log('Error handling a request: ' + e.message); console.log('Error handling a request: ' + e.message);
res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'})); res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'}));
} }
}); });
// GET products/:id // GET products/:id
productsRouter.get('/:id', async (req: Request, res: Response) => { productsRouter.get('/:id', async (req: Request, res: Response) => {
const id: number = parseInt(req.params.id, 10); const id: number = parseInt(req.params.id, 10);
if (!id) { if (!id) {
res.status(400).send('Missing parameters.'); res.status(400).send('Missing parameters.');
return; return;
} }
try { try {
const product: Product = await ProductService.find(id); const product: Product = await ProductService.find(id);
res.status(200).send(product); res.status(200).send(product);
} catch (e) { } catch (e: any) {
console.log('Error handling a request: ' + e.message); console.log('Error handling a request: ' + e.message);
res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'})); res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'}));
} }
}); });
// GET products/search/:term // GET products/search/:term
productsRouter.get('/search/:term', async (req: Request, res: Response) => { productsRouter.get('/search/:term', async (req: Request, res: Response) => {
const term: string = req.params.term; const term: string = req.params.term;
if (!term) { if (!term) {
res.status(400).send('Missing parameters.'); res.status(400).send('Missing parameters.');
return; return;
} }
try { try {
const products: Products = await ProductService.findBySearchTerm(term); const products: Products = await ProductService.findBySearchTerm(term);
res.status(200).send(products); res.status(200).send(products);
} catch (e) { } catch (e: any) {
console.log('Error handling a request: ' + e.message); console.log('Error handling a request: ' + e.message);
res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'})); res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'}));
} }
}); });
// GET products/list/[1,2,3] // GET products/list/[1,2,3]
productsRouter.get('/list/:ids', async (req: Request, res: Response) => { productsRouter.get('/list/:ids', async (req: Request, res: Response) => {
const ids: [number] = JSON.parse(req.params.ids); const ids: [number] = JSON.parse(req.params.ids);
if (!ids) { if (!ids) {
res.status(400).send('Missing parameters.'); res.status(400).send('Missing parameters.');
return; return;
} }
try { try {
const products: Products = await ProductService.findList(ids); const products: Products = await ProductService.findList(ids);
res.status(200).send(products); res.status(200).send(products);
} catch (e) { } catch (e: any) {
console.log('Error handling a request: ' + e.message); console.log('Error handling a request: ' + e.message);
res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'})); res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'}));
} }
}); });
// GET products/vendor/:id // GET products/vendor/:id
productsRouter.get('/vendor/:id', async (req: Request, res: Response) => { productsRouter.get('/vendor/:id', async (req: Request, res: Response) => {
const id: number = parseInt(req.params.id, 10); const id: number = parseInt(req.params.id, 10);
if (!id) { if (!id) {
res.status(400).send('Missing parameters.'); res.status(400).send('Missing parameters.');
return; return;
} }
try { try {
const products: Products = await ProductService.findByVendor(id); const products: Products = await ProductService.findByVendor(id);
res.status(200).send(products); res.status(200).send(products);
} catch (e) { } catch (e: any) {
console.log('Error handling a request: ' + e.message); console.log('Error handling a request: ' + e.message);
res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'})); res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'}));
} }
}); });
// POST products/ // POST products/
productsRouter.post('/', async (req: Request, res: Response) => { productsRouter.post('/', async (req: Request, res: Response) => {
const asin: string = req.body.asin; const asin: string = req.body.asin;
if (!asin) { if (!asin) {
res.status(400).send('Missing parameters.'); res.status(400).send('Missing parameters.');
return; return;
} }
try { try {
const result: boolean = await ProductService.addNewProduct(asin); const result: boolean = await ProductService.addNewProduct(asin);
if (result) { if (result) {
res.status(201).send({}); res.status(201).send({});
} else { } else {
res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'})); res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'}));
} }
} catch (e) { } catch (e: any) {
console.log('Error handling a request: ' + e.message); console.log('Error handling a request: ' + e.message);
res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'})); res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'}));
} }
}); });
+139 -158
View File
@@ -2,18 +2,10 @@ import * as dotenv from 'dotenv';
import {Product} from './product.interface'; import {Product} from './product.interface';
import {Products} from './products.interface'; import {Products} from './products.interface';
import * as http from 'http'; import * as http from 'http';
import {BetterzonDB} from '../Betterzon.db';
dotenv.config(); 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 * Data Model Interfaces
*/ */
@@ -27,54 +19,52 @@ const pool = mariadb.createPool({
* Fetches and returns all known products * Fetches and returns all known products
*/ */
export const findAll = async (): Promise<Products> => { export const findAll = async (): Promise<Products> => {
let conn; let conn = await BetterzonDB.getConnection();
let prodRows = []; let prodRows = [];
try { 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');
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) {
for (let row in rows) { if (row !== 'meta') {
if (row !== 'meta') { let prod: Product = {
let prod: Product = { asin: '',
asin: '', category_id: 0,
category_id: 0, date_added: new Date(),
date_added: new Date(), image_guid: '',
image_guid: '', is_active: false,
is_active: false, last_modified: new Date(),
last_modified: new Date(), long_description: '',
long_description: '', manufacturer_id: 0,
manufacturer_id: 0, name: '',
name: '', product_id: 0,
product_id: 0, selling_rank: '',
selling_rank: '', short_description: ''
short_description: '' };
}; const sqlProd = rows[row];
const sqlProd = rows[row];
prod.product_id = sqlProd.product_id; prod.product_id = sqlProd.product_id;
prod.name = sqlProd.name; prod.name = sqlProd.name;
prod.asin = sqlProd.asin; prod.asin = sqlProd.asin;
prod.is_active = sqlProd.is_active; prod.is_active = sqlProd.is_active;
prod.short_description = sqlProd.short_description; prod.short_description = sqlProd.short_description;
prod.long_description = sqlProd.long_description; prod.long_description = sqlProd.long_description;
prod.image_guid = sqlProd.image_guid; prod.image_guid = sqlProd.image_guid;
prod.date_added = sqlProd.date_added; prod.date_added = sqlProd.date_added;
prod.last_modified = sqlProd.last_modified; prod.last_modified = sqlProd.last_modified;
prod.manufacturer_id = sqlProd.manufacturer_id; prod.manufacturer_id = sqlProd.manufacturer_id;
prod.selling_rank = sqlProd.selling_rank; prod.selling_rank = sqlProd.selling_rank;
prod.category_id = sqlProd.category_id; prod.category_id = sqlProd.category_id;
prodRows.push(prod); prodRows.push(prod);
} }
} }
} catch (err) { } catch (err) {
throw err; throw err;
} finally { } finally {
if (conn) { // Return connection
conn.end(); await conn.end();
} }
}
return prodRows; return prodRows;
}; };
/** /**
@@ -82,26 +72,24 @@ export const findAll = async (): Promise<Products> => {
* @param id The id of the product to fetch * @param id The id of the product to fetch
*/ */
export const find = async (id: number): Promise<Product> => { export const find = async (id: number): Promise<Product> => {
let conn; let conn = await BetterzonDB.getConnection();
let prod: any; let prod: any;
try { 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);
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) {
for (let row in rows) { if (row !== 'meta') {
if (row !== 'meta') { prod = rows[row];
prod = rows[row]; }
} }
}
} catch (err) { } catch (err) {
throw err; throw err;
} finally { } finally {
if (conn) { // Return connection
conn.end(); await conn.end();
} }
}
return prod; return prod;
}; };
/** /**
@@ -109,28 +97,26 @@ export const find = async (id: number): Promise<Product> => {
* @param term the term to match * @param term the term to match
*/ */
export const findBySearchTerm = async (term: string): Promise<Products> => { export const findBySearchTerm = async (term: string): Promise<Products> => {
let conn; let conn = await BetterzonDB.getConnection();
let prodRows = []; let prodRows = [];
try { try {
conn = await pool.getConnection(); term = '%' + term + '%';
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);
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) {
for (let row in rows) { if (row !== 'meta') {
if (row !== 'meta') { prodRows.push(rows[row]);
prodRows.push(rows[row]); }
} }
}
} catch (err) { } catch (err) {
console.log(err); console.log(err);
throw err; throw err;
} finally { } finally {
if (conn) { // Return connection
conn.end(); await conn.end();
} }
}
return prodRows; return prodRows;
}; };
/** /**
@@ -138,26 +124,24 @@ export const findBySearchTerm = async (term: string): Promise<Products> => {
* @param ids The list of product ids to fetch the details for * @param ids The list of product ids to fetch the details for
*/ */
export const findList = async (ids: [number]): Promise<Products> => { export const findList = async (ids: [number]): Promise<Products> => {
let conn; let conn = await BetterzonDB.getConnection();
let prodRows = []; let prodRows = [];
try { 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]);
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) {
for (let row in rows) { if (row !== 'meta') {
if (row !== 'meta') { prodRows.push(rows[row]);
prodRows.push(rows[row]); }
} }
}
} catch (err) { } catch (err) {
throw err; throw err;
} finally { } finally {
if (conn) { // Return connection
conn.end(); await conn.end();
} }
}
return prodRows; return prodRows;
}; };
/** /**
@@ -165,37 +149,34 @@ export const findList = async (ids: [number]): Promise<Products> => {
* @param id The id of the vendor to fetch the products for * @param id The id of the vendor to fetch the products for
*/ */
export const findByVendor = async (id: number): Promise<Products> => { export const findByVendor = async (id: number): Promise<Products> => {
let conn; let conn = await BetterzonDB.getConnection();
let prodRows = []; let prodRows = [];
try { 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);
for (let row in relevantProds) {
if (row !== 'meta') {
relevant_prod_ids.push(relevantProds[row].product_id);
}
}
// Get the relevant product ids // Fetch products
let relevant_prod_ids = []; 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 (?)', [relevant_prod_ids]);
const relevantProds = await conn.query('SELECT product_id FROM prices WHERE vendor_id = ? GROUP BY product_id', id); for (let row in rows) {
for (let row in relevantProds) { if (row !== 'meta') {
if (row !== 'meta') { prodRows.push(rows[row]);
relevant_prod_ids.push(relevantProds[row].product_id); }
} }
}
// Fetch products } catch (err) {
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 (?)', [relevant_prod_ids]); throw err;
for (let row in rows) { } finally {
if (row !== 'meta') { // Return connection
prodRows.push(rows[row]); await conn.end();
} }
}
} catch (err) { return prodRows;
throw err;
} finally {
if (conn) {
conn.end();
}
}
return prodRows;
}; };
/** /**
@@ -203,26 +184,26 @@ export const findByVendor = async (id: number): Promise<Products> => {
* @param asin The amazon asin of the product to look for * @param asin The amazon asin of the product to look for
*/ */
export const addNewProduct = async (asin: string): Promise<boolean> => { export const addNewProduct = async (asin: string): Promise<boolean> => {
try { try {
let options = { let options = {
host: 'crawl.p4ddy.com', host: 'crawl.p4ddy.com',
path: '/searchNew', path: '/searchNew',
port: '443', port: '443',
method: 'POST' method: 'POST'
}; };
let req = http.request(options, res => { let req = http.request(options, res => {
return res.statusCode === 202; return res.statusCode === 202;
}); });
req.write(JSON.stringify({ req.write(JSON.stringify({
asin: asin, asin: asin,
key: process.env.CRAWLER_ACCESS_KEY key: process.env.CRAWLER_ACCESS_KEY
})); }));
req.end(); req.end();
} catch (err) { } catch (err) {
console.log(err); console.log(err);
throw(err); throw(err);
} }
return false; return false;
}; };
@@ -1,10 +1,10 @@
export interface Session { export interface Session {
session_id: number; session_id: number;
session_key: string; session_key: string;
session_key_hash: string; session_key_hash: string;
createdDate?: Date; createdDate?: Date;
lastLogin?: Date; lastLogin?: Date;
validUntil?: Date; validUntil?: Date;
validDays?: number; validDays?: number;
last_IP: string; last_IP: string;
} }
+7 -7
View File
@@ -1,9 +1,9 @@
export interface User { export interface User {
user_id: number; user_id: number;
username: string; username: string;
email: string; email: string;
password_hash: string; password_hash: string;
registration_date: Date; registration_date: Date;
last_login_date: Date; last_login_date: Date;
is_admin: boolean; is_admin: boolean;
} }
@@ -1,5 +1,5 @@
import {User} from './user.interface'; import {User} from './user.interface';
export interface Users { export interface Users {
[key: number]: User; [key: number]: User;
} }
+75 -76
View File
@@ -5,7 +5,6 @@
import express, {Request, Response} from 'express'; import express, {Request, Response} from 'express';
import * as UserService from './users.service'; import * as UserService from './users.service';
import {User} from './user.interface'; import {User} from './user.interface';
import {Users} from './users.interface';
import {Session} from './session.interface'; import {Session} from './session.interface';
@@ -22,100 +21,100 @@ export const usersRouter = express.Router();
// POST users/register // POST users/register
usersRouter.post('/register', async (req: Request, res: Response) => { usersRouter.post('/register', async (req: Request, res: Response) => {
try { try {
const username: string = req.body.username; const username: string = req.body.username;
const password: string = req.body.password; const password: string = req.body.password;
const email: string = req.body.email; const email: string = req.body.email;
const ip: string = req.connection.remoteAddress ?? ''; const ip: string = req.connection.remoteAddress ?? '';
if (!username || !password || !email) { if (!username || !password || !email) {
// Missing // Missing
res.status(400).send(JSON.stringify({message: 'Missing parameters'})); res.status(400).send(JSON.stringify({message: 'Missing parameters'}));
return; return;
} }
// Check if username and / or email are already used // Check if username and / or email are already used
const status = await UserService.checkUsernameAndEmail(username, email); const status = await UserService.checkUsernameAndEmail(username, email);
if (status.hasProblems) { if (status.hasProblems) {
// Username and/or email are duplicates, return error // Username and/or email are duplicates, return error
res.status(400).send(JSON.stringify({messages: status.messages, codes: status.codes})); res.status(400).send(JSON.stringify({messages: status.messages, codes: status.codes}));
return; return;
} }
// Create the user and a session // Create the user and a session
const session: Session = await UserService.createUser(username, password, email, ip); const session: Session = await UserService.createUser(username, password, email, ip);
// Send the session details back to the user // Send the session details back to the user
res.status(201).send({ res.status(201).send({
session_id: session.session_id, session_id: session.session_id,
session_key: session.session_key session_key: session.session_key
}); });
} catch (e) { } catch (e: any) {
console.log('Error handling a request: ' + e.message); console.log('Error handling a request: ' + e.message);
res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'})); res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'}));
} }
}); });
// POST users/login // POST users/login
usersRouter.post('/login', async (req: Request, res: Response) => { usersRouter.post('/login', async (req: Request, res: Response) => {
try { try {
const username: string = req.body.username; const username: string = req.body.username;
const password: string = req.body.password; const password: string = req.body.password;
const ip: string = req.connection.remoteAddress ?? ''; const ip: string = req.connection.remoteAddress ?? '';
if (!username || !password) { if (!username || !password) {
// Missing // Missing
res.status(400).send(JSON.stringify({message: 'Missing parameters'})); res.status(400).send(JSON.stringify({message: 'Missing parameters'}));
return; return;
} }
// Update the user entry and create a session // Update the user entry and create a session
const session: Session = await UserService.login(username, password, ip); const session: Session = await UserService.login(username, password, ip);
if (!session.session_id) { if (!session.session_id) {
// Error logging in, probably wrong username / password // Error logging in, probably wrong username / password
res.status(401).send(JSON.stringify({messages: ['Wrong username and / or password'], codes: [1, 4]})); res.status(401).send(JSON.stringify({messages: ['Wrong username and / or password'], codes: [1, 4]}));
return; return;
} }
// Send the session details back to the user // Send the session details back to the user
res.status(200).send({ res.status(200).send({
session_id: session.session_id, session_id: session.session_id,
session_key: session.session_key session_key: session.session_key
}); });
} catch (e) { } catch (e: any) {
console.log('Error handling a request: ' + e.message); console.log('Error handling a request: ' + e.message);
res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'})); res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'}));
} }
}); });
// POST users/checkSessionValid // POST users/checkSessionValid
usersRouter.post('/checkSessionValid', async (req: Request, res: Response) => { usersRouter.post('/checkSessionValid', async (req: Request, res: Response) => {
try { try {
const ip: string = req.connection.remoteAddress ?? ''; const ip: string = req.connection.remoteAddress ?? '';
const session_id = req.body.session_id; const session_id = req.body.session_id;
const session_key = req.body.session_key; const session_key = req.body.session_key;
if(!session_id || !session_key) { if (!session_id || !session_key) {
// Error logging in, probably wrong username / password // Error logging in, probably wrong username / password
res.status(401).send(JSON.stringify({messages: ['No session detected'], codes: [5]})); res.status(401).send(JSON.stringify({messages: ['No session detected'], codes: [5]}));
return; return;
} }
// Update the user entry and create a session // Update the user entry and create a session
const user: User = await UserService.checkSession(session_id, session_key, ip); const user: User = await UserService.checkSession(session_id, session_key, ip);
if (!user.user_id) { if (!user.user_id) {
// Error logging in, probably wrong username / password // Error logging in, probably wrong username / password
res.status(401).send(JSON.stringify({messages: ['Invalid session'], codes: [5]})); res.status(401).send(JSON.stringify({messages: ['Invalid session'], codes: [5]}));
return; return;
} }
// Send the session details back to the user // Send the session details back to the user
res.status(200).send(user); res.status(200).send(user);
} catch (e) { } catch (e: any) {
console.log('Error handling a request: ' + e.message); console.log('Error handling a request: ' + e.message);
res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'})); res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'}));
} }
}); });
+208 -228
View File
@@ -3,19 +3,11 @@ import * as bcrypt from 'bcrypt';
import {Guid} from 'guid-typescript'; import {Guid} from 'guid-typescript';
import {User} from './user.interface'; import {User} from './user.interface';
import {Session} from './session.interface'; import {Session} from './session.interface';
import {BetterzonDB} from '../Betterzon.db';
dotenv.config(); 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 * Data Model Interfaces
*/ */
@@ -29,56 +21,52 @@ const pool = mariadb.createPool({
* Creates a user record in the database, also creates a session. Returns the session if successful. * 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> => { export const createUser = async (username: string, password: string, email: string, ip: string): Promise<Session> => {
let conn; let conn = await BetterzonDB.getConnection();
try { try {
// Hash password and generate + hash session key // Hash password and generate + hash session key
const pwHash = bcrypt.hashSync(password, 10); const pwHash = bcrypt.hashSync(password, 10);
const sessionKey = Guid.create().toString(); const sessionKey = Guid.create().toString();
const sessionKeyHash = bcrypt.hashSync(sessionKey, 10); const sessionKeyHash = bcrypt.hashSync(sessionKey, 10);
// Create user entry in SQL // Create user entry in SQL
conn = await pool.getConnection(); const userQuery = 'INSERT INTO users (username, email, bcrypt_password_hash) VALUES (?, ?, ?) RETURNING user_id';
const userQuery = 'INSERT INTO users (username, email, bcrypt_password_hash) VALUES (?, ?, ?) RETURNING user_id'; const userIdRes = await conn.query(userQuery, [username, email, pwHash]);
const userIdRes = await conn.query(userQuery, [username, email, pwHash]); await conn.commit();
await conn.commit();
// Get user id of the created user // Get user id of the created user
let userId: number = -1; let userId: number = -1;
for (const row in userIdRes) { for (const row in userIdRes) {
if (row !== 'meta' && userIdRes[row].user_id != null) { if (row !== 'meta' && userIdRes[row].user_id != null) {
userId = userIdRes[row].user_id; userId = userIdRes[row].user_id;
} }
} }
// Create session // Create session
const sessionQuery = 'INSERT INTO sessions (user_id, session_key_hash, createdDate, lastLogin, validUntil, validDays, last_IP) VALUES (?,?,NOW(),NOW(),DATE_ADD(NOW(), INTERVAL 30 DAY),30,?) RETURNING session_id'; const sessionQuery = 'INSERT INTO sessions (user_id, session_key_hash, createdDate, lastLogin, validUntil, validDays, last_IP) VALUES (?,?,NOW(),NOW(),DATE_ADD(NOW(), INTERVAL 30 DAY),30,?) RETURNING session_id';
const sessionIdRes = await conn.query(sessionQuery, [userId, sessionKeyHash, ip]); const sessionIdRes = await conn.query(sessionQuery, [userId, sessionKeyHash, ip]);
await conn.commit(); await conn.commit();
// Get session id of the created session // Get session id of the created session
let sessionId: number = -1; let sessionId: number = -1;
for (const row in sessionIdRes) { for (const row in sessionIdRes) {
if (row !== 'meta' && sessionIdRes[row].session_id != null) { if (row !== 'meta' && sessionIdRes[row].session_id != null) {
sessionId = sessionIdRes[row].session_id; sessionId = sessionIdRes[row].session_id;
} }
} }
return { return {
session_id: sessionId, session_id: sessionId,
session_key: sessionKey, session_key: sessionKey,
session_key_hash: 'HIDDEN', session_key_hash: 'HIDDEN',
last_IP: ip last_IP: ip
}; };
} catch (err) { } catch (err) {
throw err; throw err;
} finally { } finally {
if (conn) { // Return connection
conn.end(); await conn.end();
} }
}
return {} as Session;
}; };
/** /**
@@ -86,146 +74,140 @@ export const createUser = async (username: string, password: string, email: stri
* Returns the session information in case of a successful login * Returns the session information in case of a successful login
*/ */
export const login = async (username: string, password: string, ip: string): Promise<Session> => { export const login = async (username: string, password: string, ip: string): Promise<Session> => {
let conn; let conn = await BetterzonDB.getConnection();
try { try {
// Get saved password hash // Get saved password hash
conn = await pool.getConnection(); const query = 'SELECT user_id, bcrypt_password_hash FROM users WHERE username = ?';
const query = 'SELECT user_id, bcrypt_password_hash FROM users WHERE username = ?'; const userRows = await conn.query(query, username);
const userRows = await conn.query(query, username); let savedHash = '';
let savedHash = ''; let userId = -1;
let userId = -1; for (const row in userRows) {
for (const row in userRows) { if (row !== 'meta' && userRows[row].user_id != null) {
if (row !== 'meta' && userRows[row].user_id != null) { savedHash = userRows[row].bcrypt_password_hash;
savedHash = userRows[row].bcrypt_password_hash; userId = userRows[row].user_id;
userId = userRows[row].user_id; }
} }
}
// Check for correct password // Check for correct password
if (!bcrypt.compareSync(password, savedHash)) { if (!bcrypt.compareSync(password, savedHash)) {
// Wrong password, return invalid // Wrong password, return invalid
return {} as Session; return {} as Session;
} }
// Password is valid, continue // Password is valid, continue
// Generate + hash session key // Generate + hash session key
const sessionKey = Guid.create().toString(); const sessionKey = Guid.create().toString();
const sessionKeyHash = bcrypt.hashSync(sessionKey, 10); const sessionKeyHash = bcrypt.hashSync(sessionKey, 10);
// Update user entry in SQL // Update user entry in SQL
const userQuery = 'UPDATE users SET last_login_date = NOW() WHERE user_id = ?'; const userQuery = 'UPDATE users SET last_login_date = NOW() WHERE user_id = ?';
const userIdRes = await conn.query(userQuery, userId); const userIdRes = await conn.query(userQuery, userId);
await conn.commit(); await conn.commit();
// Create session // Create session
const sessionQuery = 'INSERT INTO sessions (user_id, session_key_hash, createdDate, lastLogin, validUntil, validDays, last_IP) VALUES (?,?,NOW(),NOW(),DATE_ADD(NOW(), INTERVAL 30 DAY),30,?) RETURNING session_id'; const sessionQuery = 'INSERT INTO sessions (user_id, session_key_hash, createdDate, lastLogin, validUntil, validDays, last_IP) VALUES (?,?,NOW(),NOW(),DATE_ADD(NOW(), INTERVAL 30 DAY),30,?) RETURNING session_id';
const sessionIdRes = await conn.query(sessionQuery, [userId, sessionKeyHash, ip]); const sessionIdRes = await conn.query(sessionQuery, [userId, sessionKeyHash, ip]);
await conn.commit(); await conn.commit();
// Get session id of the created session // Get session id of the created session
let sessionId: number = -1; let sessionId: number = -1;
for (const row in sessionIdRes) { for (const row in sessionIdRes) {
if (row !== 'meta' && sessionIdRes[row].session_id != null) { if (row !== 'meta' && sessionIdRes[row].session_id != null) {
sessionId = sessionIdRes[row].session_id; sessionId = sessionIdRes[row].session_id;
} }
} }
return { return {
session_id: sessionId, session_id: sessionId,
session_key: sessionKey, session_key: sessionKey,
session_key_hash: 'HIDDEN', session_key_hash: 'HIDDEN',
last_IP: ip last_IP: ip
}; };
} catch (err) { } catch (err) {
throw err; throw err;
} finally { } finally {
if (conn) { // Return connection
conn.end(); await conn.end();
} }
}
return {} as Session;
}; };
/** /**
* Checks if the given session information are valid and returns the user information if they are * 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> => { export const checkSession = async (sessionId: string, sessionKey: string, ip: string): Promise<User> => {
let conn; let conn = await BetterzonDB.getConnection();
try { try {
// Get saved session key hash // Get saved session key hash
conn = await pool.getConnection(); const query = 'SELECT user_id, session_key_hash, validUntil FROM sessions WHERE session_id = ?';
const query = 'SELECT user_id, session_key_hash, validUntil FROM sessions WHERE session_id = ?'; const sessionRows = await conn.query(query, sessionId);
const sessionRows = await conn.query(query, sessionId); let savedHash = '';
let savedHash = ''; let userId = -1;
let userId = -1; let validUntil = new Date();
let validUntil = new Date(); for (const row in sessionRows) {
for (const row in sessionRows) { if (row !== 'meta' && sessionRows[row].user_id != null) {
if (row !== 'meta' && sessionRows[row].user_id != null) { savedHash = sessionRows[row].session_key_hash;
savedHash = sessionRows[row].session_key_hash; userId = sessionRows[row].user_id;
userId = sessionRows[row].user_id; validUntil = sessionRows[row].validUntil;
validUntil = sessionRows[row].validUntil; }
} }
}
// Check for correct key // Check for correct key
if (!bcrypt.compareSync(sessionKey, savedHash)) { if (!bcrypt.compareSync(sessionKey, savedHash)) {
// Wrong key, return invalid // Wrong key, return invalid
return {} as User; return {} as User;
} }
// Key is valid, continue // Key is valid, continue
// Check if the session is still valid // Check if the session is still valid
if (validUntil <= new Date()) { if (validUntil <= new Date()) {
// Session expired, return invalid // Session expired, return invalid
return {} as User; return {} as User;
} }
// Session still valid, continue // Session still valid, continue
// Update session entry in SQL // Update session entry in SQL
const updateSessionsQuery = 'UPDATE sessions SET lastLogin = NOW(), last_IP = ? WHERE session_id = ?'; const updateSessionsQuery = 'UPDATE sessions SET lastLogin = NOW(), last_IP = ? WHERE session_id = ?';
const updateUsersQuery = 'UPDATE users SET last_login_date = NOW() WHERE user_id = ?'; const updateUsersQuery = 'UPDATE users SET last_login_date = NOW() WHERE user_id = ?';
const userIdRes = await conn.query(updateSessionsQuery, [ip, sessionId]); const userIdRes = await conn.query(updateSessionsQuery, [ip, sessionId]);
await conn.query(updateUsersQuery, userId); await conn.query(updateUsersQuery, userId);
await conn.commit(); await conn.commit();
// Get the other required user information and update the user // Get the other required user information and update the user
const userQuery = 'SELECT user_id, username, email, registration_date, last_login_date, is_admin FROM users WHERE user_id = ?'; const userQuery = 'SELECT user_id, username, email, registration_date, last_login_date, is_admin FROM users WHERE user_id = ?';
const userRows = await conn.query(userQuery, userId); const userRows = await conn.query(userQuery, userId);
let username = ''; let username = '';
let email = ''; let email = '';
let registrationDate = new Date(); let registrationDate = new Date();
let lastLoginDate = new Date(); let lastLoginDate = new Date();
let is_admin = false; let is_admin = false;
for (const row in userRows) { for (const row in userRows) {
if (row !== 'meta' && userRows[row].user_id != null) { if (row !== 'meta' && userRows[row].user_id != null) {
username = userRows[row].username; username = userRows[row].username;
email = userRows[row].email; email = userRows[row].email;
registrationDate = userRows[row].registration_date; registrationDate = userRows[row].registration_date;
lastLoginDate = userRows[row].last_login_date; lastLoginDate = userRows[row].last_login_date;
is_admin = userRows[row].is_admin; is_admin = userRows[row].is_admin;
} }
} }
// Everything is fine, return user information // Everything is fine, return user information
return { return {
user_id: userId, user_id: userId,
username: username, username: username,
email: email, email: email,
password_hash: 'HIDDEN', password_hash: 'HIDDEN',
registration_date: registrationDate, registration_date: registrationDate,
last_login_date: lastLoginDate, last_login_date: lastLoginDate,
is_admin: is_admin is_admin: is_admin
}; };
} catch (err) { } catch (err) {
throw err; throw err;
} finally { } finally {
if (conn) { // Return connection
conn.end(); await conn.end();
} }
}
}; };
/** /**
@@ -234,21 +216,21 @@ export const checkSession = async (sessionId: string, sessionKey: string, ip: st
* @param ip The users IP address * @param ip The users IP address
*/ */
export const checkSessionWithCookie = async (cookie: any, ip: string): Promise<User> => { export const checkSessionWithCookie = async (cookie: any, ip: string): Promise<User> => {
const parsedCookie = JSON.parse(cookie); const parsedCookie = JSON.parse(cookie);
const session_id = parsedCookie.id; const session_id = parsedCookie.id;
const session_key = parsedCookie.key; const session_key = parsedCookie.key;
return checkSession(session_id, session_key, ''); return checkSession(session_id, session_key, '');
}; };
/** /**
* Used in the checkUsernameAndEmail method as return value * Used in the checkUsernameAndEmail method as return value
*/ */
export interface Status { export interface Status {
hasProblems: boolean; hasProblems: boolean;
messages: string[]; messages: string[];
codes: number[]; // 0 = all good, 1 = wrong username, 2 = wrong email, 3 = server error, 4 = wrong password, 5 = wrong session codes: number[]; // 0 = all good, 1 = wrong username, 2 = wrong email, 3 = server error, 4 = wrong password, 5 = wrong session
} }
/** /**
@@ -257,58 +239,56 @@ export interface Status {
* @param email The email to check * @param email The email to check
*/ */
export const checkUsernameAndEmail = async (username: string, email: string): Promise<Status> => { export const checkUsernameAndEmail = async (username: string, email: string): Promise<Status> => {
let conn; let conn = await BetterzonDB.getConnection();
try { try {
// Create user entry in SQL // Create user entry in SQL
conn = await pool.getConnection(); const usernameQuery = 'SELECT username FROM users WHERE username = ?';
const usernameQuery = 'SELECT username FROM users WHERE username = ?'; const emailQuery = 'SELECT email FROM users WHERE email = ?';
const emailQuery = 'SELECT email FROM users WHERE email = ?'; const usernameRes = await conn.query(usernameQuery, username);
const usernameRes = await conn.query(usernameQuery, username); const emailRes = await conn.query(emailQuery, email);
const emailRes = await conn.query(emailQuery, email);
let res: Status = { let res: Status = {
hasProblems: false, hasProblems: false,
messages: [], messages: [],
codes: [] codes: []
}; };
const usernameRegex = RegExp('^[a-zA-Z0-9\\-\\_]{4,20}$'); // Can contain a-z, A-Z, 0-9, -, _ and has to be 4-20 chars long const usernameRegex = RegExp('^[a-zA-Z0-9\\-\\_]{4,20}$'); // Can contain a-z, A-Z, 0-9, -, _ and has to be 4-20 chars long
if (!usernameRegex.test(username)) { if (!usernameRegex.test(username)) {
// Username doesn't match requirements // Username doesn't match requirements
res.hasProblems = true; res.hasProblems = true;
res.messages.push('Invalid username'); res.messages.push('Invalid username');
res.codes.push(1); res.codes.push(1);
} }
const emailRegex = RegExp('^[a-zA-Z0-9\\-\\_.]{1,30}\\@[a-zA-Z0-9\\-.]{1,20}\\.[a-z]{1,20}$'); // Normal email regex, user@betterzon.xyz const emailRegex = RegExp('^[a-zA-Z0-9\\-\\_.]{1,30}\\@[a-zA-Z0-9\\-.]{1,20}\\.[a-z]{1,20}$'); // Normal email regex, user@betterzon.xyz
if (!emailRegex.test(email)) { if (!emailRegex.test(email)) {
// Username doesn't match requirements // Username doesn't match requirements
res.hasProblems = true; res.hasProblems = true;
res.messages.push('Invalid email'); res.messages.push('Invalid email');
res.codes.push(2); res.codes.push(2);
} }
if (usernameRes.length > 0) { if (usernameRes.length > 0) {
// Username is a duplicate // Username is a duplicate
res.hasProblems = true; res.hasProblems = true;
res.messages.push('Duplicate username'); res.messages.push('Duplicate username');
res.codes.push(1); res.codes.push(1);
} }
if (emailRes.length > 0) { if (emailRes.length > 0) {
// Email is a duplicate // Email is a duplicate
res.hasProblems = true; res.hasProblems = true;
res.messages.push('Duplicate email'); res.messages.push('Duplicate email');
res.codes.push(2); res.codes.push(2);
} }
return res; return res;
} catch (err) { } catch (err) {
throw err; throw err;
} finally { } finally {
if (conn) { // Return connection
conn.end(); await conn.end();
} }
}
}; };
+8 -8
View File
@@ -1,10 +1,10 @@
export interface Vendor { export interface Vendor {
vendor_id: number; vendor_id: number;
name: string; name: string;
streetname: string; streetname: string;
zip_code: string; zip_code: string;
city: string; city: string;
country_code: string; country_code: string;
phone: string; phone: string;
website: string; website: string;
} }
+1 -1
View File
@@ -1,5 +1,5 @@
import {Vendor} from './vendor.interface'; import {Vendor} from './vendor.interface';
export interface Vendors { export interface Vendors {
[key: number]: Vendor; [key: number]: Vendor;
} }
+98 -98
View File
@@ -22,144 +22,144 @@ export const vendorsRouter = express.Router();
// GET vendors/ // GET vendors/
vendorsRouter.get('/', async (req: Request, res: Response) => { vendorsRouter.get('/', async (req: Request, res: Response) => {
try { try {
const vendors: Vendors = await VendorService.findAll(); const vendors: Vendors = await VendorService.findAll();
res.status(200).send(vendors); res.status(200).send(vendors);
} catch (e) { } catch (e: any) {
console.log('Error handling a request: ' + e.message); console.log('Error handling a request: ' + e.message);
res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'})); res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'}));
} }
}); });
// GET vendors/managed // GET vendors/managed
vendorsRouter.get('/managed', async (req: Request, res: Response) => { vendorsRouter.get('/managed', async (req: Request, res: Response) => {
try { try {
// Authenticate user // Authenticate user
const user_ip = req.connection.remoteAddress ?? ''; const user_ip = req.connection.remoteAddress ?? '';
const session_id = (req.query.session_id ?? '').toString(); const session_id = (req.query.session_id ?? '').toString();
const session_key = (req.query.session_key ?? '').toString(); const session_key = (req.query.session_key ?? '').toString();
const user = await UserService.checkSession(session_id, session_key, user_ip); const user = await UserService.checkSession(session_id, session_key, user_ip);
const vendors = await VendorService.getManagedShops(user.user_id); const vendors = await VendorService.getManagedShops(user.user_id);
res.status(200).send(vendors); res.status(200).send(vendors);
} catch (e) { } catch (e: any) {
console.log('Error handling a request: ' + e.message); console.log('Error handling a request: ' + e.message);
res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'})); res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'}));
} }
}); });
// GET vendors/:id // GET vendors/:id
vendorsRouter.get('/:id', async (req: Request, res: Response) => { vendorsRouter.get('/:id', async (req: Request, res: Response) => {
const id: number = parseInt(req.params.id, 10); const id: number = parseInt(req.params.id, 10);
if (!id) { if (!id) {
res.status(400).send('Missing parameters.'); res.status(400).send('Missing parameters.');
return; return;
} }
try { try {
const vendor: Vendor = await VendorService.find(id); const vendor: Vendor = await VendorService.find(id);
res.status(200).send(vendor); res.status(200).send(vendor);
} catch (e) { } catch (e: any) {
console.log('Error handling a request: ' + e.message); console.log('Error handling a request: ' + e.message);
res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'})); res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'}));
} }
}); });
// GET vendors/search/:term // GET vendors/search/:term
vendorsRouter.get('/search/:term', async (req: Request, res: Response) => { vendorsRouter.get('/search/:term', async (req: Request, res: Response) => {
const term: string = req.params.term; const term: string = req.params.term;
if (!term) { if (!term) {
res.status(400).send('Missing parameters.'); res.status(400).send('Missing parameters.');
return; return;
} }
try { try {
const vendors: Vendors = await VendorService.findBySearchTerm(term); const vendors: Vendors = await VendorService.findBySearchTerm(term);
res.status(200).send(vendors); res.status(200).send(vendors);
} catch (e) { } catch (e: any) {
console.log('Error handling a request: ' + e.message); console.log('Error handling a request: ' + e.message);
res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'})); res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'}));
} }
}); });
// PUT vendors/manage/deactivatelisting // PUT vendors/manage/deactivatelisting
vendorsRouter.put('/manage/deactivatelisting', async (req: Request, res: Response) => { vendorsRouter.put('/manage/deactivatelisting', async (req: Request, res: Response) => {
try { try {
// Authenticate user // Authenticate user
const user_ip = req.connection.remoteAddress ?? ''; const user_ip = req.connection.remoteAddress ?? '';
const session_id = req.body.session_id; const session_id = req.body.session_id;
const session_key = req.body.session_key; const session_key = req.body.session_key;
const user = await UserService.checkSession(session_id, session_key, user_ip); const user = await UserService.checkSession(session_id, session_key, user_ip);
// Get required parameters // Get required parameters
const vendor_id = req.body.vendor_id; const vendor_id = req.body.vendor_id;
const product_id = req.body.product_id; const product_id = req.body.product_id;
const success = await VendorService.deactivateListing(user.user_id, vendor_id, product_id); const success = await VendorService.deactivateListing(user.user_id, vendor_id, product_id);
if (success) { if (success) {
res.status(200).send({}); res.status(200).send({});
} else { } else {
res.status(500).send({}); res.status(500).send({});
} }
} catch (e) { } catch (e: any) {
console.log('Error handling a request: ' + e.message); console.log('Error handling a request: ' + e.message);
res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'})); res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'}));
} }
}); });
// PUT vendors/manage/shop/deactivate/:id // PUT vendors/manage/shop/deactivate/:id
vendorsRouter.put('/manage/shop/deactivate/:id', async (req: Request, res: Response) => { vendorsRouter.put('/manage/shop/deactivate/:id', async (req: Request, res: Response) => {
try { try {
// Authenticate user // Authenticate user
const user_ip = req.connection.remoteAddress ?? ''; const user_ip = req.connection.remoteAddress ?? '';
const session_id = req.body.session_id; const session_id = req.body.session_id;
const session_key = req.body.session_key; const session_key = req.body.session_key;
const user = await UserService.checkSession(session_id, session_key, user_ip); const user = await UserService.checkSession(session_id, session_key, user_ip);
// Get required parameters // Get required parameters
const vendor_id = parseInt(req.params.id, 10); const vendor_id = parseInt(req.params.id, 10);
const success = await VendorService.setShopStatus(user.user_id, vendor_id, false); const success = await VendorService.setShopStatus(user.user_id, vendor_id, false);
if (success) { if (success) {
res.status(200).send({}); res.status(200).send({});
} else { } else {
res.status(500).send({}); res.status(500).send({});
} }
} catch (e) { } catch (e: any) {
console.log('Error handling a request: ' + e.message); console.log('Error handling a request: ' + e.message);
res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'})); res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'}));
} }
}); });
// PUT vendors/manage/shop/activate/:id // PUT vendors/manage/shop/activate/:id
vendorsRouter.put('/manage/shop/activate/:id', async (req: Request, res: Response) => { vendorsRouter.put('/manage/shop/activate/:id', async (req: Request, res: Response) => {
try { try {
// Authenticate user // Authenticate user
const user_ip = req.connection.remoteAddress ?? ''; const user_ip = req.connection.remoteAddress ?? '';
const session_id = req.body.session_id; const session_id = req.body.session_id;
const session_key = req.body.session_key; const session_key = req.body.session_key;
const user = await UserService.checkSession(session_id, session_key, user_ip); const user = await UserService.checkSession(session_id, session_key, user_ip);
// Get required parameters // Get required parameters
const vendor_id = parseInt(req.params.id, 10); const vendor_id = parseInt(req.params.id, 10);
const success = await VendorService.setShopStatus(user.user_id, vendor_id, true); const success = await VendorService.setShopStatus(user.user_id, vendor_id, true);
if (success) { if (success) {
res.status(200).send({}); res.status(200).send({});
} else { } else {
res.status(500).send({}); res.status(500).send({});
} }
} catch (e) { } catch (e: any) {
console.log('Error handling a request: ' + e.message); console.log('Error handling a request: ' + e.message);
res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'})); res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'}));
} }
}); });
+116 -142
View File
@@ -1,18 +1,10 @@
import * as dotenv from 'dotenv'; import * as dotenv from 'dotenv';
import {Vendor} from './vendor.interface'; import {Vendor} from './vendor.interface';
import {Vendors} from './vendors.interface'; import {Vendors} from './vendors.interface';
import {BetterzonDB} from '../Betterzon.db';
dotenv.config(); 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 * Data Model Interfaces
*/ */
@@ -26,46 +18,44 @@ const pool = mariadb.createPool({
* Fetches and returns all known vendors * Fetches and returns all known vendors
*/ */
export const findAll = async (): Promise<Vendors> => { export const findAll = async (): Promise<Vendors> => {
let conn; let conn = await BetterzonDB.getConnection();
let vendorRows = []; let vendorRows = [];
try { 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');
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) {
for (let row in rows) { if (row !== 'meta') {
if (row !== 'meta') { let vendor: Vendor = {
let vendor: Vendor = { city: '',
city: '', country_code: '',
country_code: '', name: '',
name: '', phone: '',
phone: '', streetname: '',
streetname: '', vendor_id: 0,
vendor_id: 0, website: '',
website: '', zip_code: ''
zip_code: '' };
}; const sqlVendor = rows[row];
const sqlVendor = rows[row];
vendor.vendor_id = sqlVendor.vendor_id; vendor.vendor_id = sqlVendor.vendor_id;
vendor.name = sqlVendor.name; vendor.name = sqlVendor.name;
vendor.streetname = sqlVendor.streetname; vendor.streetname = sqlVendor.streetname;
vendor.zip_code = sqlVendor.zip_code; vendor.zip_code = sqlVendor.zip_code;
vendor.city = sqlVendor.city; vendor.city = sqlVendor.city;
vendor.country_code = sqlVendor.country_code; vendor.country_code = sqlVendor.country_code;
vendor.phone = sqlVendor.phone; vendor.phone = sqlVendor.phone;
vendor.website = sqlVendor.website; vendor.website = sqlVendor.website;
vendorRows.push(vendor); vendorRows.push(vendor);
} }
} }
} catch (err) { } catch (err) {
throw err; throw err;
} finally { } finally {
if (conn) { // Return connection
conn.end(); await conn.end();
} }
}
return vendorRows; return vendorRows;
}; };
/** /**
@@ -73,26 +63,24 @@ export const findAll = async (): Promise<Vendors> => {
* @param id The id of the vendor to fetch * @param id The id of the vendor to fetch
*/ */
export const find = async (id: number): Promise<Vendor> => { export const find = async (id: number): Promise<Vendor> => {
let conn; let conn = await BetterzonDB.getConnection();
let vendor: any; let vendor: any;
try { 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);
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) {
for (let row in rows) { if (row !== 'meta') {
if (row !== 'meta') { vendor = rows[row];
vendor = rows[row]; }
} }
}
} catch (err) { } catch (err) {
throw err; throw err;
} finally { } finally {
if (conn) { // Return connection
conn.end(); await conn.end();
} }
}
return vendor; return vendor;
}; };
/** /**
@@ -100,27 +88,25 @@ export const find = async (id: number): Promise<Vendor> => {
* @param term the term to match * @param term the term to match
*/ */
export const findBySearchTerm = async (term: string): Promise<Vendors> => { export const findBySearchTerm = async (term: string): Promise<Vendors> => {
let conn; let conn = await BetterzonDB.getConnection();
let vendorRows = []; let vendorRows = [];
try { try {
conn = await pool.getConnection(); term = '%' + term + '%';
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);
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) {
for (let row in rows) { if (row !== 'meta') {
if (row !== 'meta') { vendorRows.push(rows[row]);
vendorRows.push(rows[row]); }
} }
}
} catch (err) { } catch (err) {
throw err; throw err;
} finally { } finally {
if (conn) { // Return connection
conn.end(); await conn.end();
} }
}
return vendorRows; return vendorRows;
}; };
/** /**
@@ -128,26 +114,24 @@ export const findBySearchTerm = async (term: string): Promise<Vendors> => {
* @param user The user to return the managed shops for * @param user The user to return the managed shops for
*/ */
export const getManagedShops = async (user_id: number): Promise<Vendors> => { export const getManagedShops = async (user_id: number): Promise<Vendors> => {
let conn; let conn = await BetterzonDB.getConnection();
let vendorRows = []; let vendorRows = [];
try { 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);
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) {
for (let row in rows) { if (row !== 'meta') {
if (row !== 'meta') { vendorRows.push(rows[row]);
vendorRows.push(rows[row]); }
} }
}
} catch (err) { } catch (err) {
throw err; throw err;
} finally { } finally {
if (conn) { // Return connection
conn.end(); await conn.end();
} }
}
return vendorRows; return vendorRows;
}; };
/** /**
@@ -157,28 +141,23 @@ export const getManagedShops = async (user_id: number): Promise<Vendors> => {
* @param product_id The product id of the product to deactivate the listing for * @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> => { export const deactivateListing = async (user_id: number, vendor_id: number, product_id: number): Promise<Boolean> => {
let conn; let conn = await BetterzonDB.getConnection();
try { 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) {
return false;
}
// Check if the user is authorized to manage the requested vendor const status = await conn.query('UPDATE prices SET active_listing = false WHERE vendor_id = ? and product_id = ?', [vendor_id, product_id]);
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) {
return false;
}
const status = await conn.query('UPDATE prices SET active_listing = false WHERE vendor_id = ? and product_id = ?', [vendor_id, product_id]); return status.affectedRows > 0;
} catch (err) {
return status.affectedRows > 0; throw err;
} catch (err) { } finally {
throw err; // Return connection
} finally { await conn.end();
if (conn) { }
conn.end();
}
}
return false;
}; };
/** /**
@@ -188,27 +167,22 @@ export const deactivateListing = async (user_id: number, vendor_id: number, prod
* @param isActive The new active state * @param isActive The new active state
*/ */
export const setShopStatus = async (user_id: number, vendor_id: number, isActive: boolean): Promise<Boolean> => { export const setShopStatus = async (user_id: number, vendor_id: number, isActive: boolean): Promise<Boolean> => {
let conn; let conn = await BetterzonDB.getConnection();
try { 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) {
return false;
}
// Check if the user is authorized to manage the requested vendor // Update the vendor state
const user_vendor_rows = await conn.query('SELECT vendor_id FROM vendors WHERE vendor_id = ? AND admin_id = ?', [vendor_id, user_id]); const status = await conn.query('UPDATE vendors SET isActive = ? WHERE vendor_id = ?', [isActive, vendor_id]);
if (user_vendor_rows.length !== 1) {
return false;
}
// Update the vendor state return status.affectedRows > 0;
const status = await conn.query('UPDATE vendors SET isActive = ? WHERE vendor_id = ?', [isActive, vendor_id]); } catch (err) {
throw err;
return status.affectedRows > 0; } finally {
} catch (err) { // Return connection
throw err; await conn.end();
} finally { }
if (conn) {
conn.end();
}
}
return false;
}; };
@@ -0,0 +1,19 @@
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();
};
}
@@ -0,0 +1,35 @@
/**
* 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
});
}
});
@@ -0,0 +1,6 @@
export interface ClimbingGym {
gym_id: number;
name: string;
city: string;
verified: boolean;
}
@@ -0,0 +1,152 @@
/**
* 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
});
}
});
@@ -0,0 +1,39 @@
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();
}
};
@@ -0,0 +1,7 @@
export interface ClimbingRoute {
route_id: string;
gym_id: number;
name: string;
difficulty: string;
route_setting_date: Date;
}
@@ -0,0 +1,226 @@
/**
* 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
});
}
});
@@ -0,0 +1,68 @@
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();
}
};
@@ -0,0 +1,15 @@
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;
};
@@ -0,0 +1,6 @@
export interface RouteComment {
comment_id: number;
route_id: string;
comment: string;
timestamp: Date;
}
@@ -0,0 +1,155 @@
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
});
}
});
@@ -0,0 +1,38 @@
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();
}
};
@@ -0,0 +1,6 @@
export interface RouteRating {
rating_id: number;
route_id: string;
stars: number;
timestamp: Date;
}
@@ -0,0 +1,140 @@
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
});
}
});
@@ -0,0 +1,58 @@
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();
}
};
@@ -0,0 +1,19 @@
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();
};
}
@@ -12,37 +12,37 @@ import * as ChangeService from './changes/changes.service';
export const dhbwRaPlaChangesRouter = express.Router(); export const dhbwRaPlaChangesRouter = express.Router();
dhbwRaPlaChangesRouter.get('/', async (req: Request, res: Response) => { dhbwRaPlaChangesRouter.get('/', async (req: Request, res: Response) => {
try { try {
let week = (req.query.week ?? '').toString(); let week = (req.query.week ?? '').toString();
let changes = await ChangeService.getChanges('TINF19B4', week); let changes = await ChangeService.getChanges('TINF19B4', week);
res.status(200).send(changes); res.status(200).send(changes);
} catch (e) { } catch (e: any) {
let errorGuid = Guid.create().toString(); let errorGuid = Guid.create().toString();
logger.error('Error handling a request: ' + e.message, {reference: errorGuid}); logger.error('Error handling a request: ' + e.message, {reference: errorGuid});
res.status(500).send({ res.status(500).send({
'status': 'PROCESSING_ERROR', 'status': 'PROCESSING_ERROR',
'message': 'Internal Server Error. Try again later.', 'message': 'Internal Server Error. Try again later.',
'reference': errorGuid 'reference': errorGuid
}); });
} }
}); });
dhbwRaPlaChangesRouter.get('/:id', async (req: Request, res: Response) => { dhbwRaPlaChangesRouter.get('/:id', async (req: Request, res: Response) => {
try { try {
let id: string = (req.params.id ?? '').toString(); let id: string = (req.params.id ?? '').toString();
let changes = await ChangeService.getEventById('TINF19B4', id); let changes = await ChangeService.getEventById('TINF19B4', id);
res.status(200).send(changes); res.status(200).send(changes);
} catch (e) { } catch (e: any) {
let errorGuid = Guid.create().toString(); let errorGuid = Guid.create().toString();
logger.error('Error handling a request: ' + e.message, {reference: errorGuid}); logger.error('Error handling a request: ' + e.message, {reference: errorGuid});
res.status(500).send({ res.status(500).send({
'status': 'PROCESSING_ERROR', 'status': 'PROCESSING_ERROR',
'message': 'Internal Server Error. Try again later.', 'message': 'Internal Server Error. Try again later.',
'reference': errorGuid 'reference': errorGuid
}); });
} }
}); });
@@ -1,16 +1,16 @@
export interface Change { export interface Change {
change_id: string; change_id: string;
event_id: string; event_id: string;
change_timestamp: Date; change_timestamp: Date;
is_deleted: boolean; is_deleted: boolean;
new_summary: string; new_summary: string;
new_description: string; new_description: string;
new_start: Date; new_start: Date;
new_end: Date; new_end: Date;
new_last_modified: Date; new_last_modified: Date;
new_created: Date; new_created: Date;
new_location: string; new_location: string;
new_organizer: string; new_organizer: string;
new_categories: string; new_categories: string;
new_recurring: string; new_recurring: string;
} }
@@ -1,9 +1,9 @@
import {Change} from './Change.interface'; import {Change} from './Change.interface';
export interface Event { export interface Event {
event_id: string; event_id: string;
event_uid: string; event_uid: string;
latest_event_summary: string; latest_event_summary: string;
latest_start_date: Date; latest_start_date: Date;
changes: Change[]; changes: Change[];
} }
@@ -1,147 +1,133 @@
import * as dotenv from 'dotenv'; import * as dotenv from 'dotenv';
import {Event} from './Event.interface'; import {Event} from './Event.interface';
import {Change} from './Change.interface'; import {Change} from './Change.interface';
import {RaPlaChangesDB} from '../DHBWRaPlaChanges.db';
dotenv.config(); 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[]> => { export const getChanges = async (course: string, week: string): Promise<Event[]> => {
let conn; let conn = await RaPlaChangesDB.getConnection();
try { 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 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[] = [];
relevantEventsRows.forEach((row: { entry_id: string; }) => {
relevantEventIds.push(row.entry_id);
});
let relevantEventIds: string[] = []; if (relevantEventIds.length < 1) {
relevantEventsRows.forEach((row: { entry_id: string; }) => { return [];
relevantEventIds.push(row.entry_id); }
});
if (relevantEventIds.length < 1) { 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 c.entry_id IN (?) ORDER BY c.change_id', [relevantEventIds]);
return [];
}
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 c.entry_id IN (?) ORDER BY c.change_id', [relevantEventIds]); let eventsMap = new Map();
let eventsMap = new Map(); for (let row of rows) {
let change: Change = {
change_id: row.change_id,
event_id: row.event_id,
change_timestamp: row.change_timestamp,
is_deleted: row.isDeleted,
new_summary: row.new_summary,
new_description: row.new_description,
new_start: row.new_start,
new_end: row.new_end,
new_last_modified: row.new_last_modified,
new_created: row.new_created,
new_location: row.new_location,
new_organizer: row.new_organizer,
new_categories: row.new_categories,
new_recurring: row.new_recurring
};
for (let row of rows) { if (eventsMap.has(row.entry_id)) {
let change: Change = { let event = eventsMap.get(row.entry_id);
change_id: row.change_id,
event_id: row.event_id,
change_timestamp: row.change_timestamp,
is_deleted: row.isDeleted,
new_summary: row.new_summary,
new_description: row.new_description,
new_start: row.new_start,
new_end: row.new_end,
new_last_modified: row.new_last_modified,
new_created: row.new_created,
new_location: row.new_location,
new_organizer: row.new_organizer,
new_categories: row.new_categories,
new_recurring: row.new_recurring
};
if (eventsMap.has(row.entry_id)) { // Only adjust these fields if the event is not deleted as otherwise they would be null
let event = eventsMap.get(row.entry_id); if (!row.isDeleted) {
event.latest_event_summary = row.new_summary;
event.latest_start_date = row.new_start;
}
event.changes.push(change);
// Only adjust these fields if the event is not deleted as otherwise they would be null eventsMap.set(row.entry_id, event);
if (!row.isDeleted) { } else {
event.latest_event_summary = row.new_summary; let event: Event = {
event.latest_start_date = row.new_start; event_id: row.event_id,
} event_uid: row.uid,
event.changes.push(change); latest_event_summary: row.new_summary,
latest_start_date: row.new_start,
changes: [change]
};
eventsMap.set(row.entry_id, event); eventsMap.set(row.entry_id, event);
} else { }
let event: Event = { }
event_id: row.event_id,
event_uid: row.uid,
latest_event_summary: row.new_summary,
latest_start_date: row.new_start,
changes: [change]
};
eventsMap.set(row.entry_id, event); return Array.from(eventsMap.values()) as Event[];
} } catch (err) {
} throw err;
} finally {
return Array.from(eventsMap.values()) as Event[]; // Return connection
} catch (err) { await conn.end();
throw err; }
} finally {
if (conn) {
conn.end();
}
}
}; };
export const getEventById = async (course: string, id: string): Promise<Event> => { export const getEventById = async (course: string, id: string): Promise<Event> => {
let conn; let conn = await RaPlaChangesDB.getConnection();
try { 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 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();
let eventsMap = new Map(); for (let row of rows) {
let change: Change = {
change_id: row.change_id,
event_id: row.event_id,
change_timestamp: row.change_timestamp,
is_deleted: row.isDeleted,
new_summary: row.new_summary,
new_description: row.new_description,
new_start: row.new_start,
new_end: row.new_end,
new_last_modified: row.new_last_modified,
new_created: row.new_created,
new_location: row.new_location,
new_organizer: row.new_organizer,
new_categories: row.new_categories,
new_recurring: row.new_recurring
};
for (let row of rows) { if (eventsMap.has(row.entry_id)) {
let change: Change = { let event = eventsMap.get(row.entry_id);
change_id: row.change_id,
event_id: row.event_id,
change_timestamp: row.change_timestamp,
is_deleted: row.isDeleted,
new_summary: row.new_summary,
new_description: row.new_description,
new_start: row.new_start,
new_end: row.new_end,
new_last_modified: row.new_last_modified,
new_created: row.new_created,
new_location: row.new_location,
new_organizer: row.new_organizer,
new_categories: row.new_categories,
new_recurring: row.new_recurring
};
if (eventsMap.has(row.entry_id)) { // Only adjust these fields if the event is not deleted as otherwise they would be null
let event = eventsMap.get(row.entry_id); if (!row.isDeleted) {
event.latest_event_summary = row.new_summary;
event.latest_start_date = row.new_start;
}
event.changes.push(change);
// Only adjust these fields if the event is not deleted as otherwise they would be null eventsMap.set(row.entry_id, event);
if (!row.isDeleted) { } else {
event.latest_event_summary = row.new_summary; let event: Event = {
event.latest_start_date = row.new_start; event_id: row.event_id,
} event_uid: row.uid,
event.changes.push(change); latest_event_summary: row.new_summary,
latest_start_date: row.new_start,
changes: [change]
};
eventsMap.set(row.entry_id, event); eventsMap.set(row.entry_id, event);
} else { }
let event: Event = { }
event_id: row.event_id,
event_uid: row.uid,
latest_event_summary: row.new_summary,
latest_start_date: row.new_start,
changes: [change]
};
eventsMap.set(row.entry_id, event); return Array.from(eventsMap.values())[0];
} } catch (err) {
} throw err;
} finally {
return Array.from(eventsMap.values())[0]; // Return connection
} catch (err) { await conn.end();
throw err; }
} finally {
if (conn) {
conn.end();
}
}
}; };
+11 -11
View File
@@ -15,15 +15,15 @@ export const dhbwServiceRouter = express.Router();
dhbwServiceRouter.use('/generalInfo', generalInfoRouter); dhbwServiceRouter.use('/generalInfo', generalInfoRouter);
dhbwServiceRouter.get('/', async (req: Request, res: Response) => { dhbwServiceRouter.get('/', async (req: Request, res: Response) => {
try { try {
res.status(200).send('Pluto Development DHBW Service App API Endpoint'); res.status(200).send('Pluto Development DHBW Service App API Endpoint');
} catch (e) { } catch (e: any) {
let errorGuid = Guid.create().toString(); let errorGuid = Guid.create().toString();
logger.error('Error handling a request: ' + e.message, {reference: errorGuid}); logger.error('Error handling a request: ' + e.message, {reference: errorGuid});
res.status(500).send({ res.status(500).send({
'status': 'PROCESSING_ERROR', 'status': 'PROCESSING_ERROR',
'message': 'Internal Server Error. Try again later.', 'message': 'Internal Server Error. Try again later.',
'reference': errorGuid 'reference': errorGuid
}); });
} }
}); });
@@ -11,29 +11,29 @@ import {Guid} from 'guid-typescript';
export const generalInfoRouter = express.Router(); export const generalInfoRouter = express.Router();
generalInfoRouter.get('/', async (req: Request, res: Response) => { generalInfoRouter.get('/', async (req: Request, res: Response) => {
try { try {
res.status(200).send('GET generalInfo v2.1'); res.status(200).send('GET generalInfo v2.1');
} catch (e) { } catch (e: any) {
let errorGuid = Guid.create().toString(); let errorGuid = Guid.create().toString();
logger.error('Error handling a request: ' + e.message, {reference: errorGuid}); logger.error('Error handling a request: ' + e.message, {reference: errorGuid});
res.status(500).send({ res.status(500).send({
'status': 'PROCESSING_ERROR', 'status': 'PROCESSING_ERROR',
'message': 'Internal Server Error. Try again later.', 'message': 'Internal Server Error. Try again later.',
'reference': errorGuid 'reference': errorGuid
}); });
} }
}); });
generalInfoRouter.post('/', async (req: Request, res: Response) => { generalInfoRouter.post('/', async (req: Request, res: Response) => {
try { try {
res.status(200).send('POST generalInfo v2.1'); res.status(200).send('POST generalInfo v2.1');
} catch (e) { } catch (e: any) {
let errorGuid = Guid.create().toString(); let errorGuid = Guid.create().toString();
logger.error('Error handling a request: ' + e.message, {reference: errorGuid}); logger.error('Error handling a request: ' + e.message, {reference: errorGuid});
res.status(500).send({ res.status(500).send({
'status': 'PROCESSING_ERROR', 'status': 'PROCESSING_ERROR',
'message': 'Internal Server Error. Try again later.', 'message': 'Internal Server Error. Try again later.',
'reference': errorGuid 'reference': errorGuid
}); });
} }
}); });
+29
View File
@@ -0,0 +1,29 @@
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();
};
}
+11 -11
View File
@@ -27,15 +27,15 @@ partyPlanerRouter.use('/session', sessionRouter);
partyPlanerRouter.use('/user', userRouter); partyPlanerRouter.use('/user', userRouter);
partyPlanerRouter.get('/', async (req: Request, res: Response) => { partyPlanerRouter.get('/', async (req: Request, res: Response) => {
try { try {
res.status(200).send('Pluto Development PartyPlaner API Endpoint V2'); res.status(200).send('Pluto Development PartyPlaner API Endpoint V2');
} catch (e) { } catch (e: any) {
let errorGuid = Guid.create().toString(); let errorGuid = Guid.create().toString();
logger.error('Error handling a request: ' + e.message, {reference: errorGuid}); logger.error('Error handling a request: ' + e.message, {reference: errorGuid});
res.status(500).send({ res.status(500).send({
'status': 'PROCESSING_ERROR', 'status': 'PROCESSING_ERROR',
'message': 'Internal Server Error. Try again later.', 'message': 'Internal Server Error. Try again later.',
'reference': errorGuid 'reference': errorGuid
}); });
} }
}); });
@@ -5,12 +5,12 @@ import {Registration} from './Registration.interface';
* Used in the getEventData method as a return value * Used in the getEventData method as a return value
*/ */
export interface Event { export interface Event {
eventId: string; eventId: string;
name: string; name: string;
description: string; description: string;
takesPlaceDate: Date; takesPlaceDate: Date;
registrationUntilDate: Date; registrationUntilDate: Date;
maxParticipants: number; maxParticipants: number;
invites: Invite[]; invites: Invite[];
registrations: Registration[]; registrations: Registration[];
} }
+30 -31
View File
@@ -13,39 +13,38 @@ import {Guid} from 'guid-typescript';
export const eventRouter = express.Router(); export const eventRouter = express.Router();
eventRouter.get('/:isDevCall', async (req: Request, res: Response) => { eventRouter.get('/:isDevCall', async (req: Request, res: Response) => {
try { try {
throw new Error('Test'); let userId = (req.query.userId ?? '').toString();
let userId = (req.query.userId ?? '').toString(); let sessionId = (req.query.sessionId ?? '').toString();
let sessionId = (req.query.sessionId ?? '').toString(); let sessionKey = (req.query.sessionKey ?? '').toString();
let sessionKey = (req.query.sessionKey ?? '').toString(); let useDev: boolean = (req.params.isDevCall ?? '') === 'dev'; // TBD
let useDev: boolean = (req.params.isDevCall ?? '') === 'dev'; // TBD
if (userId === '' || sessionId === '' || sessionKey === '') { if (userId === '' || sessionId === '' || sessionKey === '') {
res.status(400).send({ res.status(400).send({
'status': 'WRONG_PARAMS', 'status': 'WRONG_PARAMS',
'message': 'Missing or wrong parameters' 'message': 'Missing or wrong parameters'
}); });
return; return;
} }
if (!await UserService.checkSession(useDev, userId, sessionId, sessionKey)) { if (!await UserService.checkSession(useDev, userId, sessionId, sessionKey)) {
res.status(403).send({ res.status(403).send({
'status': 'INVALID_SESSION', 'status': 'INVALID_SESSION',
'message': 'The user or session could not be found or the session is invalid' 'message': 'The user or session could not be found or the session is invalid'
}); });
return; return;
} }
let data = await EventService.getEventData(useDev, userId); let data = await EventService.getEventData(useDev, userId);
res.status(200).send(data); res.status(200).send(data);
} catch (e) { } catch (e: any) {
let errorGuid = Guid.create().toString(); let errorGuid = Guid.create().toString();
logger.error('Error handling a request: ' + e.message, {reference: errorGuid}); logger.error('Error handling a request: ' + e.message, {reference: errorGuid});
res.status(500).send({ res.status(500).send({
'status': 'PROCESSING_ERROR', 'status': 'PROCESSING_ERROR',
'message': 'Internal Server Error. Try again later.', 'message': 'Internal Server Error. Try again later.',
'reference': errorGuid 'reference': errorGuid
}); });
} }
}); });
@@ -2,9 +2,9 @@
* Used in the getEventData method * Used in the getEventData method
*/ */
export interface Invite { export interface Invite {
inviteId: string; inviteId: string;
inviteKey: string; inviteKey: string;
validUntil: Date; validUntil: Date;
alreadyUsed: boolean; alreadyUsed: boolean;
invitedPersonName: string; invitedPersonName: string;
} }
@@ -2,9 +2,9 @@
* Used in the getEventData method * Used in the getEventData method
*/ */
export interface Registration { export interface Registration {
registrationId: string; registrationId: string;
name: string; name: string;
registeredDate: Date; registeredDate: Date;
takesPart: boolean; takesPart: boolean;
comment: string; comment: string;
} }
+55 -77
View File
@@ -1,24 +1,9 @@
import * as dotenv from 'dotenv'; import * as dotenv from 'dotenv';
import {Event} from './Event.interface'; import {Event} from './Event.interface';
import {PartyPlanerDB} from '../PartyPlaner.db';
dotenv.config(); 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 * Returns all events of the given user
* @param useDev If the dev or prod database should be used * @param useDev If the dev or prod database should be used
@@ -26,73 +11,66 @@ const dev_pool = mariadb.createPool({
* @return Event[] A list of events * @return Event[] A list of events
*/ */
export const getEventData = async (useDev: boolean, userId: string): Promise<Event[]> => { export const getEventData = async (useDev: boolean, userId: string): Promise<Event[]> => {
let conn; let conn = await PartyPlanerDB.getConnection(useDev);
try { try {
if (useDev) { let eventRows = await conn.query('SELECT event_id, name, description, takes_place_date, registration_until_date, max_participants FROM events WHERE creator_id = ?', userId);
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>();
let eventIds: string[] = [];
let eventsMap = new Map<string, Event>(); for (let row of eventRows) {
let eventIds: string[] = []; eventIds.push(row.event_id);
let event = {
eventId: row.event_id,
name: row.name,
description: row.description,
takesPlaceDate: row.takes_place_date,
registrationUntilDate: row.registration_until_date,
maxParticipants: row.max_participants,
invites: [],
registrations: []
};
eventsMap.set(row.event_id, event);
}
for (let row of eventRows) { let registrationRows = await conn.query('SELECT registration_id, name, registered_date, takes_part, comment, event_id FROM event_registration WHERE event_id IN (?)', eventIds);
eventIds.push(row.event_id);
let event = {
eventId: row.event_id,
name: row.name,
description: row.description,
takesPlaceDate: row.takes_place_date,
registrationUntilDate: row.registration_until_date,
maxParticipants: row.max_participants,
invites: [],
registrations: []
};
eventsMap.set(row.event_id, event);
}
let registrationRows = await conn.query('SELECT registration_id, name, registered_date, takes_part, comment, event_id FROM event_registration WHERE event_id IN (?)', eventIds); for (let row of registrationRows) {
let event = eventsMap.get(row.event_id);
if (!event) continue;
event.registrations.push({
registrationId: row.registration_id,
name: row.name,
registeredDate: row.registered_date,
takesPart: row.takes_part,
comment: row.comment
});
}
for (let row of registrationRows) { let inviteRows = await conn.query('SELECT invite_id, invite_key, valid_until, already_used, invited_person_name, event_id FROM invitations WHERE event_id IN (?)', eventIds);
let event = eventsMap.get(row.event_id);
if (!event) continue;
event.registrations.push({
registrationId: row.registration_id,
name: row.name,
registeredDate: row.registered_date,
takesPart: row.takes_part,
comment: row.comment
});
}
let inviteRows = await conn.query('SELECT invite_id, invite_key, valid_until, already_used, invited_person_name, event_id FROM invitations WHERE event_id IN (?)', eventIds); for (let row of inviteRows) {
let event = eventsMap.get(row.event_id);
if (!event) continue;
event.invites.push({
inviteId: row.invite_id,
inviteKey: row.invite_key,
validUntil: row.valid_until,
alreadyUsed: row.already_used,
invitedPersonName: row.invited_person_name
});
}
for (let row of inviteRows) { let eventsList: Event[] = [];
let event = eventsMap.get(row.event_id); for (let event of eventsMap.values()) {
if (!event) continue; eventsList.push(event);
event.invites.push({ }
inviteId: row.invite_id,
inviteKey: row.invite_key,
validUntil: row.valid_until,
alreadyUsed: row.already_used,
invitedPersonName: row.invited_person_name
});
}
let eventsList: Event[] = []; return eventsList;
for (let event of eventsMap.values()) { } catch (err) {
eventsList.push(event); throw err;
} } finally {
// Return connection
return eventsList; await conn.end();
} catch (err) { }
throw err;
} finally {
if (conn) {
conn.end();
}
}
}; };
@@ -2,9 +2,9 @@
* Used in the getFriendshipData method as a return value * Used in the getFriendshipData method as a return value
*/ */
export interface Friendship { export interface Friendship {
friendshipId: string; friendshipId: string;
friendId: string; friendId: string;
friendFirstName: string; friendFirstName: string;
friendLastName: string; friendLastName: string;
friendUsername: string; friendUsername: string;
} }
@@ -13,38 +13,38 @@ import {Guid} from 'guid-typescript';
export const friendshipRouter = express.Router(); export const friendshipRouter = express.Router();
friendshipRouter.get('/:isDevCall', async (req: Request, res: Response) => { friendshipRouter.get('/:isDevCall', async (req: Request, res: Response) => {
try { try {
let userId = (req.query.userId ?? '').toString(); let userId = (req.query.userId ?? '').toString();
let sessionId = (req.query.sessionId ?? '').toString(); let sessionId = (req.query.sessionId ?? '').toString();
let sessionKey = (req.query.sessionKey ?? '').toString(); let sessionKey = (req.query.sessionKey ?? '').toString();
let useDev: boolean = (req.params.isDevCall ?? '') === 'dev'; // TBD let useDev: boolean = (req.params.isDevCall ?? '') === 'dev'; // TBD
if (userId === '' || sessionId === '' || sessionKey === '') { if (userId === '' || sessionId === '' || sessionKey === '') {
res.status(400).send({ res.status(400).send({
'status': 'WRONG_PARAMS', 'status': 'WRONG_PARAMS',
'message': 'Missing or wrong parameters' 'message': 'Missing or wrong parameters'
}); });
return; return;
} }
if (!await UserService.checkSession(useDev, userId, sessionId, sessionKey)) { if (!await UserService.checkSession(useDev, userId, sessionId, sessionKey)) {
res.status(403).send({ res.status(403).send({
'status': 'INVALID_SESSION', 'status': 'INVALID_SESSION',
'message': 'The user or session could not be found or the session is invalid' 'message': 'The user or session could not be found or the session is invalid'
}); });
return; return;
} }
let data = await FriendshipService.getFriendshipData(useDev, userId); let data = await FriendshipService.getFriendshipData(useDev, userId);
res.status(200).send(data); res.status(200).send(data);
} catch (e) { } catch (e: any) {
let errorGuid = Guid.create().toString(); let errorGuid = Guid.create().toString();
logger.error('Error handling a request: ' + e.message, {reference: errorGuid}); logger.error('Error handling a request: ' + e.message, {reference: errorGuid});
res.status(500).send({ res.status(500).send({
'status': 'PROCESSING_ERROR', 'status': 'PROCESSING_ERROR',
'message': 'Internal Server Error. Try again later.', 'message': 'Internal Server Error. Try again later.',
'reference': errorGuid 'reference': errorGuid
}); });
} }
}); });
@@ -1,24 +1,9 @@
import * as dotenv from 'dotenv'; import * as dotenv from 'dotenv';
import {Friendship} from './Friendship.interface'; import {Friendship} from './Friendship.interface';
import {PartyPlanerDB} from '../PartyPlaner.db';
dotenv.config(); 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 * Returns all friends of the given user
* @param useDev If the dev or prod database should be used * @param useDev If the dev or prod database should be used
@@ -26,34 +11,27 @@ const dev_pool = mariadb.createPool({
* @return Friendship[] A list of friends * @return Friendship[] A list of friends
*/ */
export const getFriendshipData = async (useDev: boolean, userId: string): Promise<Friendship[]> => { export const getFriendshipData = async (useDev: boolean, userId: string): Promise<Friendship[]> => {
let conn; let conn = await PartyPlanerDB.getConnection(useDev);
try { try {
if (useDev) { 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);
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[] = [];
let friends: Friendship[] = []; for (let row of rows) {
friends.push({
friendshipId: row.friendship_id,
friendId: row.friend_id,
friendFirstName: row.friend_first_name,
friendLastName: row.friend_last_name,
friendUsername: row.friend_username
});
}
for (let row of rows) { return friends;
friends.push({ } catch (err) {
friendshipId: row.friendship_id, throw err;
friendId: row.friend_id, } finally {
friendFirstName: row.friend_first_name, // Return connection
friendLastName: row.friend_last_name, await conn.end();
friendUsername: row.friend_username }
});
}
return friends;
} catch (err) {
throw err;
} finally {
if (conn) {
conn.end();
}
}
}; };
+30 -30
View File
@@ -13,38 +13,38 @@ import {Guid} from 'guid-typescript';
export const inviteRouter = express.Router(); export const inviteRouter = express.Router();
inviteRouter.get('/:isDevCall', async (req: Request, res: Response) => { inviteRouter.get('/:isDevCall', async (req: Request, res: Response) => {
try { try {
let userId = (req.query.userId ?? '').toString(); let userId = (req.query.userId ?? '').toString();
let sessionId = (req.query.sessionId ?? '').toString(); let sessionId = (req.query.sessionId ?? '').toString();
let sessionKey = (req.query.sessionKey ?? '').toString(); let sessionKey = (req.query.sessionKey ?? '').toString();
let useDev: boolean = (req.params.isDevCall ?? '') === 'dev'; // TBD let useDev: boolean = (req.params.isDevCall ?? '') === 'dev'; // TBD
if (userId === '' || sessionId === '' || sessionKey === '') { if (userId === '' || sessionId === '' || sessionKey === '') {
res.status(400).send({ res.status(400).send({
'status': 'WRONG_PARAMS', 'status': 'WRONG_PARAMS',
'message': 'Missing or wrong parameters' 'message': 'Missing or wrong parameters'
}); });
return; return;
} }
if (!await UserService.checkSession(useDev, userId, sessionId, sessionKey)) { if (!await UserService.checkSession(useDev, userId, sessionId, sessionKey)) {
res.status(403).send({ res.status(403).send({
'status': 'INVALID_SESSION', 'status': 'INVALID_SESSION',
'message': 'The user or session could not be found or the session is invalid' 'message': 'The user or session could not be found or the session is invalid'
}); });
return; return;
} }
let data = await InviteService.getInvitesData(useDev, userId); let data = await InviteService.getInvitesData(useDev, userId);
res.status(200).send(data); res.status(200).send(data);
} catch (e) { } catch (e: any) {
let errorGuid = Guid.create().toString(); let errorGuid = Guid.create().toString();
logger.error('Error handling a request: ' + e.message, {reference: errorGuid}); logger.error('Error handling a request: ' + e.message, {reference: errorGuid});
res.status(500).send({ res.status(500).send({
'status': 'PROCESSING_ERROR', 'status': 'PROCESSING_ERROR',
'message': 'Internal Server Error. Try again later.', 'message': 'Internal Server Error. Try again later.',
'reference': errorGuid 'reference': errorGuid
}); });
} }
}); });
@@ -2,16 +2,16 @@
* Used in the getInvitesData method as a return value * Used in the getInvitesData method as a return value
*/ */
export interface ReceivedInvite { export interface ReceivedInvite {
inviteId: string; inviteId: string;
validUntil: Date; validUntil: Date;
alreadyUsed: boolean; alreadyUsed: boolean;
inviteKey: string; inviteKey: string;
eventName: string; eventName: string;
eventDescription: string; eventDescription: string;
takesPlaceDate: Date; takesPlaceDate: Date;
registrationUntilDate: Date; registrationUntilDate: Date;
maxParticipants: number; maxParticipants: number;
eventCreatorId: string; eventCreatorId: string;
creatorFirstName: string; creatorFirstName: string;
creatorLastName: string; creatorLastName: string;
} }
+28 -50
View File
@@ -1,24 +1,9 @@
import * as dotenv from 'dotenv'; import * as dotenv from 'dotenv';
import {ReceivedInvite} from './ReceivedInvite.interface'; import {ReceivedInvite} from './ReceivedInvite.interface';
import {PartyPlanerDB} from '../PartyPlaner.db';
dotenv.config(); 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 * Returns all events the user is invited to
* @param useDev If the dev or prod database should be used * @param useDev If the dev or prod database should be used
@@ -26,41 +11,34 @@ const dev_pool = mariadb.createPool({
* @return ReceivedInvite[] A list of invites * @return ReceivedInvite[] A list of invites
*/ */
export const getInvitesData = async (useDev: boolean, userId: string): Promise<ReceivedInvite[]> => { export const getInvitesData = async (useDev: boolean, userId: string): Promise<ReceivedInvite[]> => {
let conn; let conn = await PartyPlanerDB.getConnection(useDev);
try { try {
if (useDev) { 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);
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[] = [];
let invites: ReceivedInvite[] = []; for (let row of rows) {
invites.push({
inviteId: row.invite_id,
validUntil: row.valid_until,
alreadyUsed: row.already_used,
inviteKey: row.invite_key,
eventName: row.event_name,
eventDescription: row.event_description,
takesPlaceDate: row.takes_place_date,
registrationUntilDate: row.registration_until_date,
maxParticipants: row.max_participants,
eventCreatorId: row.creator_id,
creatorFirstName: row.first_name,
creatorLastName: row.last_name
});
}
for (let row of rows) { return invites;
invites.push({ } catch (err) {
inviteId: row.invite_id, throw err;
validUntil: row.valid_until, } finally {
alreadyUsed: row.already_used, // Return connection
inviteKey: row.invite_key, await conn.end();
eventName: row.event_name, }
eventDescription: row.event_description,
takesPlaceDate: row.takes_place_date,
registrationUntilDate: row.registration_until_date,
maxParticipants: row.max_participants,
eventCreatorId: row.creator_id,
creatorFirstName: row.first_name,
creatorLastName: row.last_name
});
}
return invites;
} catch (err) {
throw err;
} finally {
if (conn) {
conn.end();
}
}
}; };
+50 -50
View File
@@ -12,59 +12,59 @@ import {Guid} from 'guid-typescript';
export const loginRouter = express.Router(); export const loginRouter = express.Router();
loginRouter.post('/:isDevCall', async (req: Request, res: Response) => { loginRouter.post('/:isDevCall', async (req: Request, res: Response) => {
try { try {
let username: string = ''; let username: string = '';
let email: string = ''; let email: string = '';
let password: string = ''; let password: string = '';
let useDev: boolean = (req.params.isDevCall ?? '') === 'dev'; // TBD let useDev: boolean = (req.params.isDevCall ?? '') === 'dev'; // TBD
// Send error when content-type header is missing // Send error when content-type header is missing
if (!req.headers['content-type']) { if (!req.headers['content-type']) {
res.status(400).send({ res.status(400).send({
'status': 'MISSING_CONTENT_TYPE', 'status': 'MISSING_CONTENT_TYPE',
'message': 'Please set the content-type header field' 'message': 'Please set the content-type header field'
}); });
return; return;
} }
// API accepts both JSON in body and HTTP parameters // API accepts both JSON in body and HTTP parameters
if (req.headers['content-type'] === 'application/json') { if (req.headers['content-type'] === 'application/json') {
username = req.body.username; username = req.body.username;
email = req.body.email; email = req.body.email;
password = req.body.password; password = req.body.password;
} else if (req.headers['content-type'] === 'application/x-www-form-urlencoded') { } else if (req.headers['content-type'] === 'application/x-www-form-urlencoded') {
username = (req.query.username ?? '').toString(); username = (req.query.username ?? '').toString();
email = (req.query.email ?? '').toString(); email = (req.query.email ?? '').toString();
password = (req.query.password ?? '').toString(); password = (req.query.password ?? '').toString();
} else { } else {
res.status(400).send({ res.status(400).send({
'status': 'WRONG_CONTENT_TYPE', 'status': 'WRONG_CONTENT_TYPE',
'message': 'The transmitted content-type is not supported' 'message': 'The transmitted content-type is not supported'
}); });
return; return;
} }
let userIP = req.socket.remoteAddress ?? ''; let userIP = req.socket.remoteAddress ?? '';
let deviceInfo = req.headers['user-agent'] ?? ''; let deviceInfo = req.headers['user-agent'] ?? '';
if ((username === '' && email === '') || password === '') { if ((username === '' && email === '') || password === '') {
res.status(400).send({ res.status(400).send({
'status': 'WRONG_PARAMS', 'status': 'WRONG_PARAMS',
'message': 'Missing or wrong parameters' 'message': 'Missing or wrong parameters'
}); });
return; return;
} }
// Check password and create session // Check password and create session
let session = await UserService.loginUser(useDev, username, email, password, userIP, deviceInfo); let session = await UserService.loginUser(useDev, username, email, password, userIP, deviceInfo);
res.status(200).send(session); res.status(200).send(session);
} catch (e) { } catch (e: any) {
let errorGuid = Guid.create().toString(); let errorGuid = Guid.create().toString();
logger.error('Error handling a request: ' + e.message, {reference: errorGuid}); logger.error('Error handling a request: ' + e.message, {reference: errorGuid});
res.status(500).send({ res.status(500).send({
'status': 'PROCESSING_ERROR', 'status': 'PROCESSING_ERROR',
'message': 'Internal Server Error. Try again later.', 'message': 'Internal Server Error. Try again later.',
'reference': errorGuid 'reference': errorGuid
}); });
} }
}); });
@@ -12,78 +12,78 @@ import {Guid} from 'guid-typescript';
export const registerRouter = express.Router(); export const registerRouter = express.Router();
registerRouter.post('/:isDevCall', async (req: Request, res: Response) => { registerRouter.post('/:isDevCall', async (req: Request, res: Response) => {
try { try {
let username: string = ''; let username: string = '';
let email: string = ''; let email: string = '';
let firstName: string = ''; let firstName: string = '';
let lastName: string = ''; let lastName: string = '';
let password: string = ''; let password: string = '';
let useDev: boolean = (req.params.isDevCall ?? '') === 'dev'; // TBD let useDev: boolean = (req.params.isDevCall ?? '') === 'dev'; // TBD
// Send error when content-type header is missing // Send error when content-type header is missing
if (!req.headers['content-type']) { if (!req.headers['content-type']) {
res.status(400).send({ res.status(400).send({
'status': 'MISSING_CONTENT_TYPE', 'status': 'MISSING_CONTENT_TYPE',
'message': 'Please set the content-type header field' 'message': 'Please set the content-type header field'
}); });
return; return;
} }
// API accepts both JSON in body and HTTP parameters // API accepts both JSON in body and HTTP parameters
if (req.headers['content-type'] === 'application/json') { if (req.headers['content-type'] === 'application/json') {
username = req.body.username; username = req.body.username;
email = req.body.email; email = req.body.email;
firstName = req.body.firstName; firstName = req.body.firstName;
lastName = req.body.lastName; lastName = req.body.lastName;
password = req.body.password; password = req.body.password;
} else if (req.headers['content-type'] === 'application/x-www-form-urlencoded') { } else if (req.headers['content-type'] === 'application/x-www-form-urlencoded') {
username = (req.query.username ?? '').toString(); username = (req.query.username ?? '').toString();
email = (req.query.email ?? '').toString(); email = (req.query.email ?? '').toString();
firstName = (req.query.firstName ?? '').toString(); firstName = (req.query.firstName ?? '').toString();
lastName = (req.query.lastName ?? '').toString(); lastName = (req.query.lastName ?? '').toString();
password = (req.query.password ?? '').toString(); password = (req.query.password ?? '').toString();
} else { } else {
res.status(400).send({ res.status(400).send({
'status': 'WRONG_CONTENT_TYPE', 'status': 'WRONG_CONTENT_TYPE',
'message': 'The transmitted content-type is not supported' 'message': 'The transmitted content-type is not supported'
}); });
return; return;
} }
let userIP = req.socket.remoteAddress ?? ''; let userIP = req.socket.remoteAddress ?? '';
let deviceInfo = req.headers['user-agent'] ?? ''; let deviceInfo = req.headers['user-agent'] ?? '';
if (username === '' || email === '' || firstName === '' || lastName === '' || password === '') { if (username === '' || email === '' || firstName === '' || lastName === '' || password === '') {
res.status(400).send({ res.status(400).send({
'status': 'WRONG_PARAMS', 'status': 'WRONG_PARAMS',
'message': 'Missing or wrong parameters' 'message': 'Missing or wrong parameters'
}); });
return; return;
} }
// Check for invalid username / email // Check for invalid username / email
const status = await UserService.checkUsernameAndEmail(useDev, username, email); const status = await UserService.checkUsernameAndEmail(useDev, username, email);
if (status.hasProblems) { if (status.hasProblems) {
// Username and/or email are duplicates, return error // Username and/or email are duplicates, return error
res.status(400).send({ res.status(400).send({
'message': status.messages[0], 'message': status.messages[0],
'status': status.status[0], 'status': status.status[0],
'additionalMessages': status.messages.slice(1), 'additionalMessages': status.messages.slice(1),
'additionalStatus': status.status.slice(1) 'additionalStatus': status.status.slice(1)
}); });
return; return;
} }
// Create user // Create user
let session = await UserService.registerUser(useDev, username, email, firstName, lastName, password, userIP, deviceInfo); let session = await UserService.registerUser(useDev, username, email, firstName, lastName, password, userIP, deviceInfo);
res.status(201).send(session); res.status(201).send(session);
} catch (e) { } catch (e: any) {
let errorGuid = Guid.create().toString(); let errorGuid = Guid.create().toString();
logger.error('Error handling a request: ' + e.message, {reference: errorGuid}); logger.error('Error handling a request: ' + e.message, {reference: errorGuid});
res.status(500).send({ res.status(500).send({
'status': 'PROCESSING_ERROR', 'status': 'PROCESSING_ERROR',
'message': 'Internal Server Error. Try again later.', 'message': 'Internal Server Error. Try again later.',
'reference': errorGuid 'reference': errorGuid
}); });
} }
}); });
@@ -13,38 +13,38 @@ import {Guid} from 'guid-typescript';
export const sessionRouter = express.Router(); export const sessionRouter = express.Router();
sessionRouter.get('/:isDevCall', async (req: Request, res: Response) => { sessionRouter.get('/:isDevCall', async (req: Request, res: Response) => {
try { try {
let userId = (req.query.userId ?? '').toString(); let userId = (req.query.userId ?? '').toString();
let sessionId = (req.query.sessionId ?? '').toString(); let sessionId = (req.query.sessionId ?? '').toString();
let sessionKey = (req.query.sessionKey ?? '').toString(); let sessionKey = (req.query.sessionKey ?? '').toString();
let useDev: boolean = (req.params.isDevCall ?? '') === 'dev'; // TBD let useDev: boolean = (req.params.isDevCall ?? '') === 'dev'; // TBD
if (userId === '' || sessionId === '' || sessionKey === '') { if (userId === '' || sessionId === '' || sessionKey === '') {
res.status(400).send({ res.status(400).send({
'status': 'WRONG_PARAMS', 'status': 'WRONG_PARAMS',
'message': 'Missing or wrong parameters' 'message': 'Missing or wrong parameters'
}); });
return; return;
} }
if (!await UserService.checkSession(useDev, userId, sessionId, sessionKey)) { if (!await UserService.checkSession(useDev, userId, sessionId, sessionKey)) {
res.status(403).send({ res.status(403).send({
'status': 'INVALID_SESSION', 'status': 'INVALID_SESSION',
'message': 'The user or session could not be found or the session is invalid' 'message': 'The user or session could not be found or the session is invalid'
}); });
return; return;
} }
let data = await SessionService.getSessionData(useDev, userId); let data = await SessionService.getSessionData(useDev, userId);
res.status(200).send(data); res.status(200).send(data);
} catch (e) { } catch (e: any) {
let errorGuid = Guid.create().toString(); let errorGuid = Guid.create().toString();
logger.error('Error handling a request: ' + e.message, {reference: errorGuid}); logger.error('Error handling a request: ' + e.message, {reference: errorGuid});
res.status(500).send({ res.status(500).send({
'status': 'PROCESSING_ERROR', 'status': 'PROCESSING_ERROR',
'message': 'Internal Server Error. Try again later.', 'message': 'Internal Server Error. Try again later.',
'reference': errorGuid 'reference': errorGuid
}); });
} }
}); });
@@ -2,8 +2,8 @@
* Used in the getSessionData method as return value * Used in the getSessionData method as return value
*/ */
export interface SessionData { export interface SessionData {
sessionId: string; sessionId: string;
type: string; type: string;
lastLogin: string; lastLogin: string;
lastIp: string; lastIp: string;
} }
@@ -1,24 +1,9 @@
import * as dotenv from 'dotenv'; import * as dotenv from 'dotenv';
import {SessionData} from './SessionData.interface'; import {SessionData} from './SessionData.interface';
import {PartyPlanerDB} from '../PartyPlaner.db';
dotenv.config(); 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 * Returns all active sessions of the given user
* @param useDev If the dev or prod database should be used * @param useDev If the dev or prod database should be used
@@ -26,33 +11,26 @@ const dev_pool = mariadb.createPool({
* @return SessionData[] A list containing objects with the session data * @return SessionData[] A list containing objects with the session data
*/ */
export const getSessionData = async (useDev: boolean, userId: string): Promise<SessionData[]> => { export const getSessionData = async (useDev: boolean, userId: string): Promise<SessionData[]> => {
let conn; let conn = await PartyPlanerDB.getConnection(useDev);
try { try {
if (useDev) { let rows = await conn.query('SELECT session_id, type, last_login, last_ip FROM sessions WHERE user_id = ? AND valid_until > NOW()', userId);
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[] = [];
let sessions: SessionData[] = []; for (let row of rows) {
sessions.push({
sessionId: row.session_id,
type: row.type,
lastLogin: row.last_login,
lastIp: row.last_ip
});
}
for (let row of rows) { return sessions;
sessions.push({ } catch (err) {
sessionId: row.session_id, throw err;
type: row.type, } finally {
lastLogin: row.last_login, // Return connection
lastIp: row.last_ip await conn.end();
}); }
}
return sessions;
} catch (err) {
throw err;
} finally {
if (conn) {
conn.end();
}
}
}; };
@@ -2,7 +2,7 @@
* Used in the registerUser and loginUser methods as return value * Used in the registerUser and loginUser methods as return value
*/ */
export interface Session { export interface Session {
userId: string; userId: string;
sessionId: string; sessionId: string;
sessionKey: string; sessionKey: string;
} }
@@ -2,7 +2,7 @@
* Used in the checkUsernameAndEmail method as return value * Used in the checkUsernameAndEmail method as return value
*/ */
export interface Status { export interface Status {
hasProblems: boolean; hasProblems: boolean;
messages: string[]; messages: string[];
status: string[]; status: string[];
} }
+30 -30
View File
@@ -12,38 +12,38 @@ import {Guid} from 'guid-typescript';
export const userRouter = express.Router(); export const userRouter = express.Router();
userRouter.get('/:isDevCall', async (req: Request, res: Response) => { userRouter.get('/:isDevCall', async (req: Request, res: Response) => {
try { try {
let userId = (req.query.userId ?? '').toString(); let userId = (req.query.userId ?? '').toString();
let sessionId = (req.query.sessionId ?? '').toString(); let sessionId = (req.query.sessionId ?? '').toString();
let sessionKey = (req.query.sessionKey ?? '').toString(); let sessionKey = (req.query.sessionKey ?? '').toString();
let useDev: boolean = (req.params.isDevCall ?? '') === 'dev'; // TBD let useDev: boolean = (req.params.isDevCall ?? '') === 'dev'; // TBD
if (userId === '' || sessionId === '' || sessionKey === '') { if (userId === '' || sessionId === '' || sessionKey === '') {
res.status(400).send({ res.status(400).send({
'status': 'WRONG_PARAMS', 'status': 'WRONG_PARAMS',
'message': 'Missing or wrong parameters' 'message': 'Missing or wrong parameters'
}); });
return; return;
} }
if (!await UserService.checkSession(useDev, userId, sessionId, sessionKey)) { if (!await UserService.checkSession(useDev, userId, sessionId, sessionKey)) {
res.status(403).send({ res.status(403).send({
'status': 'INVALID_SESSION', 'status': 'INVALID_SESSION',
'message': 'The user or session could not be found or the session is invalid' 'message': 'The user or session could not be found or the session is invalid'
}); });
return; return;
} }
let data = await UserService.getUserData(useDev, userId); let data = await UserService.getUserData(useDev, userId);
res.status(200).send(data); res.status(200).send(data);
} catch (e) { } catch (e: any) {
let errorGuid = Guid.create().toString(); let errorGuid = Guid.create().toString();
logger.error('Error handling a request: ' + e.message, {reference: errorGuid}); logger.error('Error handling a request: ' + e.message, {reference: errorGuid});
res.status(500).send({ res.status(500).send({
'status': 'PROCESSING_ERROR', 'status': 'PROCESSING_ERROR',
'message': 'Internal Server Error. Try again later.', 'message': 'Internal Server Error. Try again later.',
'reference': errorGuid 'reference': errorGuid
}); });
} }
}); });
@@ -2,11 +2,11 @@
* Used in the getUserData method as return value * Used in the getUserData method as return value
*/ */
export interface UserData { export interface UserData {
username: string; username: string;
email: string; email: string;
firstName: string; firstName: string;
lastName: string; lastName: string;
lastLogin: string; lastLogin: string;
emailIsVerified: string; emailIsVerified: string;
isPremiumUser: string; isPremiumUser: string;
} }
+197 -253
View File
@@ -4,25 +4,10 @@ import {Guid} from 'guid-typescript';
import {UserData} from './UserData.interface'; import {UserData} from './UserData.interface';
import {Session} from './Session.interface'; import {Session} from './Session.interface';
import {Status} from './Status.interface'; import {Status} from './Status.interface';
import {PartyPlanerDB} from '../PartyPlaner.db';
dotenv.config(); 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 * Returns all data about the given user
* @param useDev If the dev or prod database should be used * @param useDev If the dev or prod database should be used
@@ -30,38 +15,31 @@ const dev_pool = mariadb.createPool({
* @return UserData An object containing the user data * @return UserData An object containing the user data
*/ */
export const getUserData = async (useDev: boolean, userId: string): Promise<UserData> => { export const getUserData = async (useDev: boolean, userId: string): Promise<UserData> => {
let conn; let conn = await PartyPlanerDB.getConnection(useDev);
try { try {
if (useDev) { 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);
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;
let user: UserData = {} as UserData; for (let row of rows) {
user = {
username: row.username,
email: row.email,
firstName: row.first_name,
lastName: row.last_name,
lastLogin: row.last_login,
emailIsVerified: row.email_is_verified,
isPremiumUser: row.is_premium_user
};
}
for (let row of rows) { return user;
user = { } catch (err) {
username: row.username, throw err;
email: row.email, } finally {
firstName: row.first_name, // Return connection
lastName: row.last_name, await conn.end();
lastLogin: row.last_login, }
emailIsVerified: row.email_is_verified,
isPremiumUser: row.is_premium_user
};
}
return user;
} catch (err) {
throw err;
} finally {
if (conn) {
conn.end();
}
}
}; };
/** /**
@@ -70,35 +48,28 @@ export const getUserData = async (useDev: boolean, userId: string): Promise<User
* @return any An object with a list of usernames and emails * @return any An object with a list of usernames and emails
*/ */
export const getExistingUsernamesAndEmails = async (useDev: boolean): Promise<any> => { export const getExistingUsernamesAndEmails = async (useDev: boolean): Promise<any> => {
let conn; let conn = await PartyPlanerDB.getConnection(useDev);
try { try {
if (useDev) { const rows = await conn.query('SELECT username, email FROM users');
conn = await dev_pool.getConnection();
} else {
conn = await prod_pool.getConnection();
}
const rows = await conn.query('SELECT username, email FROM users'); let usernames: string[] = [];
let emails: string[] = [];
let usernames: string[] = []; for (let row of rows) {
let emails: string[] = []; usernames.push(row.username);
emails.push(row.email);
}
for (let row of rows) { return {
usernames.push(row.username); 'usernames': usernames,
emails.push(row.email); 'emails': emails
} };
} catch (err) {
return { throw err;
'usernames': usernames, } finally {
'emails': emails // Return connection
}; await conn.end();
} catch (err) { }
throw err;
} finally {
if (conn) {
conn.end();
}
}
}; };
/** /**
@@ -113,64 +84,57 @@ export const getExistingUsernamesAndEmails = async (useDev: boolean): Promise<an
* @param deviceInfo The user agent of the new user * @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> => { export const registerUser = async (useDev: boolean, username: string, email: string, firstName: string, lastName: string, password: string, ip: string, deviceInfo: string): Promise<Session> => {
let conn; let conn = await PartyPlanerDB.getConnection(useDev);
try { try {
if (useDev) { const pwHash = bcrypt.hashSync(password, 10);
conn = await dev_pool.getConnection(); const sessionKey = Guid.create().toString();
} else { const sessionKeyHash = bcrypt.hashSync(sessionKey, 10);
conn = await prod_pool.getConnection(); const verifyEmailCode = Guid.create().toString();
}
const pwHash = bcrypt.hashSync(password, 10); // Create user
const sessionKey = Guid.create().toString(); const userQuery = 'INSERT INTO users (username, email, first_name, last_name, password_hash, verify_email_code, registration_date, last_login) VALUES (?, ?, ?, ?, ?, ?, NOW(), NOW()) RETURNING user_id';
const sessionKeyHash = bcrypt.hashSync(sessionKey, 10); const userIdRes = await conn.query(userQuery, [username, email, firstName, lastName, pwHash, verifyEmailCode]);
const verifyEmailCode = Guid.create().toString(); await conn.commit();
// Create user // Get user id of the created user
const userQuery = 'INSERT INTO users (username, email, first_name, last_name, password_hash, verify_email_code, registration_date, last_login) VALUES (?, ?, ?, ?, ?, ?, NOW(), NOW()) RETURNING user_id'; let userId: number = -1;
const userIdRes = await conn.query(userQuery, [username, email, firstName, lastName, pwHash, verifyEmailCode]); for (const row of userIdRes) {
await conn.commit(); if (row.user_id != null) {
userId = row.user_id;
}
}
// Get user id of the created user let deviceType = 'unknown';
let userId: number = -1; if (deviceInfo.includes('PartyPlaner') || deviceInfo.includes('Dart')) {
for (const row of userIdRes) { deviceType = 'mobile';
if (row.user_id != null) { } else {
userId = row.user_id; deviceType = 'desktop';
} }
}
let deviceType = 'unknown'; // Create session
if (deviceInfo.includes('PartyPlaner') || deviceInfo.includes('Dart')) { const sessionQuery = 'INSERT INTO sessions (user_id, session_key_hash, created_Date, last_login, valid_until, valid_days, last_ip, device_info, type) VALUES (?,?,NOW(),NOW(),DATE_ADD(NOW(), INTERVAL 365 DAY),365,?, ?, ?) RETURNING session_id';
deviceType = 'mobile'; const sessionIdRes = await conn.query(sessionQuery, [userId, sessionKeyHash, ip, deviceInfo, deviceType]);
} else { await conn.commit();
deviceType = 'desktop';
}
// Create session // Get session id of the created session
const sessionQuery = 'INSERT INTO sessions (user_id, session_key_hash, created_Date, last_login, valid_until, valid_days, last_ip, device_info, type) VALUES (?,?,NOW(),NOW(),DATE_ADD(NOW(), INTERVAL 365 DAY),365,?, ?, ?) RETURNING session_id'; let sessionId: number = -1;
const sessionIdRes = await conn.query(sessionQuery, [userId, sessionKeyHash, ip, deviceInfo, deviceType]); for (const row of sessionIdRes) {
await conn.commit(); if (row.session_id != null) {
sessionId = row.session_id;
}
}
// Get session id of the created session return {
let sessionId: number = -1; 'userId': userId.toString(),
for (const row of sessionIdRes) { 'sessionId': sessionId.toString(),
if (row.session_id != null) { 'sessionKey': sessionKey
sessionId = row.session_id; };
} } catch (err) {
} throw err;
} finally {
return { // Return connection
'userId': userId.toString(), await conn.end();
'sessionId': sessionId.toString(), }
'sessionKey': sessionKey
};
} catch (err) {
throw err;
} finally {
if (conn) {
conn.end();
}
}
}; };
/** /**
@@ -183,76 +147,69 @@ export const registerUser = async (useDev: boolean, username: string, email: str
* @param deviceInfo The user agent of the new user * @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> => { export const loginUser = async (useDev: boolean, username: string, email: string, password: string, ip: string, deviceInfo: string): Promise<Session> => {
let conn; let conn = await PartyPlanerDB.getConnection(useDev);
try { try {
if (useDev) { let query_result;
conn = await dev_pool.getConnection();
} else {
conn = await prod_pool.getConnection();
}
let query_result; // Get the saved hash
if (username !== '') {
query_result = await conn.query('SELECT user_id, password_hash FROM users WHERE username = ?', username);
} else {
query_result = await conn.query('SELECT user_id, password_hash FROM users WHERE email = ?', email);
}
// Get the saved hash let passwordHash: string = '';
if (username !== '') { let userId: string = '';
query_result = await conn.query('SELECT user_id, password_hash FROM users WHERE username = ?', username);
} else {
query_result = await conn.query('SELECT user_id, password_hash FROM users WHERE email = ?', email);
}
let passwordHash: string = ''; for (let row of query_result) {
let userId: string = ''; passwordHash = row.password_hash;
userId = row.user_id;
}
for (let row of query_result) { // Wrong password
passwordHash = row.password_hash; if (!bcrypt.compareSync(password, passwordHash)) {
userId = row.user_id; return {} as Session;
} }
// Wrong password // Update user last login
if (!bcrypt.compareSync(password, passwordHash)) { await conn.query('UPDATE users SET last_login = NOW() WHERE user_id = ?', userId);
return {} as Session; await conn.commit();
}
// Update user last login // Create session
await conn.query('UPDATE users SET last_login = NOW() WHERE user_id = ?', userId); const sessionKey = Guid.create().toString();
await conn.commit(); const sessionKeyHash = bcrypt.hashSync(sessionKey, 10);
// Create session let deviceType = 'unknown';
const sessionKey = Guid.create().toString(); if (deviceInfo.includes('PartyPlaner') || deviceInfo.includes('Dart')) {
const sessionKeyHash = bcrypt.hashSync(sessionKey, 10); deviceType = 'mobile';
} else {
deviceType = 'desktop';
}
let deviceType = 'unknown'; const sessionQuery = 'INSERT INTO sessions (user_id, session_key_hash, created_Date, last_login, valid_until, valid_days, last_ip, device_info, type) VALUES (?,?,NOW(),NOW(),DATE_ADD(NOW(), INTERVAL 365 DAY),365,?, ?, ?) RETURNING session_id';
if (deviceInfo.includes('PartyPlaner') || deviceInfo.includes('Dart')) { const sessionIdRes = await conn.query(sessionQuery, [userId, sessionKeyHash, ip, deviceInfo, deviceType]);
deviceType = 'mobile'; await conn.commit();
} else {
deviceType = 'desktop';
}
const sessionQuery = 'INSERT INTO sessions (user_id, session_key_hash, created_Date, last_login, valid_until, valid_days, last_ip, device_info, type) VALUES (?,?,NOW(),NOW(),DATE_ADD(NOW(), INTERVAL 365 DAY),365,?, ?, ?) RETURNING session_id'; // Get session id of the created session
const sessionIdRes = await conn.query(sessionQuery, [userId, sessionKeyHash, ip, deviceInfo, deviceType]); let sessionId: number = -1;
await conn.commit(); for (const row of sessionIdRes) {
if (row.session_id != null) {
sessionId = row.session_id;
}
}
// Get session id of the created session return {
let sessionId: number = -1; 'userId': userId.toString(),
for (const row of sessionIdRes) { 'sessionId': sessionId.toString(),
if (row.session_id != null) { 'sessionKey': sessionKey
sessionId = row.session_id; };
}
}
return { } catch (err) {
'userId': userId.toString(), throw err;
'sessionId': sessionId.toString(), } finally {
'sessionKey': sessionKey // Return connection
}; await conn.end();
}
} catch (err) {
throw err;
} finally {
if (conn) {
conn.end();
}
}
}; };
/** /**
@@ -262,87 +219,74 @@ export const loginUser = async (useDev: boolean, username: string, email: string
* @param email The email to check * @param email The email to check
*/ */
export const checkUsernameAndEmail = async (useDev: boolean, username: string, email: string): Promise<Status> => { export const checkUsernameAndEmail = async (useDev: boolean, username: string, email: string): Promise<Status> => {
let conn; let conn = await PartyPlanerDB.getConnection(useDev);
try { try {
if (useDev) { const usernameQuery = 'SELECT username FROM users WHERE username = ?';
conn = await dev_pool.getConnection(); const emailQuery = 'SELECT email FROM users WHERE email = ?';
} else { const usernameRes = await conn.query(usernameQuery, username);
conn = await prod_pool.getConnection(); const emailRes = await conn.query(emailQuery, email);
}
const usernameQuery = 'SELECT username FROM users WHERE username = ?';
const emailQuery = 'SELECT email FROM users WHERE email = ?';
const usernameRes = await conn.query(usernameQuery, username);
const emailRes = await conn.query(emailQuery, email);
let res: Status = { let res: Status = {
hasProblems: false, hasProblems: false,
messages: [], messages: [],
status: [] status: []
}; };
const usernameRegex = RegExp('^[a-zA-Z0-9\\-\\_]{4,20}$'); // Can contain a-z, A-Z, 0-9, -, _ and has to be 4-20 chars long const usernameRegex = RegExp('^[a-zA-Z0-9\\-\\_]{4,20}$'); // Can contain a-z, A-Z, 0-9, -, _ and has to be 4-20 chars long
if (!usernameRegex.test(username)) { if (!usernameRegex.test(username)) {
// Username doesn't match requirements // Username doesn't match requirements
res.hasProblems = true; res.hasProblems = true;
res.messages.push('The username contains illegal characters or is not the allowed size'); res.messages.push('The username contains illegal characters or is not the allowed size');
res.status.push('INVALID_USERNAME'); res.status.push('INVALID_USERNAME');
} }
const emailRegex = RegExp('^[a-zA-Z0-9\\-\\_.]{1,30}\\@[a-zA-Z0-9\\-.]{1,20}\\.[a-z]{1,20}$'); // Normal email regex, user@plutodev.de const emailRegex = RegExp('^[a-zA-Z0-9\\-\\_.]{1,30}\\@[a-zA-Z0-9\\-.]{1,20}\\.[a-z]{1,20}$'); // Normal email regex, user@plutodev.de
if (!emailRegex.test(email)) { if (!emailRegex.test(email)) {
// Username doesn't match requirements // Username doesn't match requirements
res.hasProblems = true; res.hasProblems = true;
res.messages.push('The email contains illegal characters or is not the allowed size'); res.messages.push('The email contains illegal characters or is not the allowed size');
res.status.push('INVALID_EMAIL'); res.status.push('INVALID_EMAIL');
} }
if (usernameRes.length > 0) { if (usernameRes.length > 0) {
// Username is a duplicate // Username is a duplicate
res.hasProblems = true; res.hasProblems = true;
res.messages.push('This username is already in use'); res.messages.push('This username is already in use');
res.status.push('DUPLICATE_USERNAME'); res.status.push('DUPLICATE_USERNAME');
} }
if (emailRes.length > 0) { if (emailRes.length > 0) {
// Email is a duplicate // Email is a duplicate
res.hasProblems = true; res.hasProblems = true;
res.messages.push('This email is already in use'); res.messages.push('This email is already in use');
res.status.push('DUPLICATE_EMAIL'); res.status.push('DUPLICATE_EMAIL');
} }
return res; return res;
} catch (err) { } catch (err) {
throw err; throw err;
} finally { } finally {
if (conn) { // Return connection
conn.end(); await conn.end();
} }
}
}; };
export const checkSession = async (useDev: boolean, userId: string, sessionId: string, sessionKey: string): Promise<boolean> => { export const checkSession = async (useDev: boolean, userId: string, sessionId: string, sessionKey: string): Promise<boolean> => {
let conn; let conn = await PartyPlanerDB.getConnection(useDev);
try { try {
if (useDev) { let rows = await conn.query('SELECT session_key_hash FROM sessions WHERE user_id = ? AND session_id = ?', [userId, sessionId]);
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 = '';
for (let row of rows) {
savedHash = row.session_key_hash;
}
let savedHash = ''; return bcrypt.compareSync(sessionKey, savedHash);
for (let row of rows) { } catch (err) {
savedHash = row.session_key_hash; throw err;
} } finally {
// Return connection
return bcrypt.compareSync(sessionKey, savedHash); await conn.end();
} catch (err) { }
throw err;
} finally {
if (conn) {
conn.end();
}
}
}; };
@@ -11,35 +11,88 @@ import * as icalgenerator from './icalgenerator/icalgenerator.service';
*/ */
export const raPlaMiddlewareRouter = express.Router(); 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) => { raPlaMiddlewareRouter.get('/', async (req: Request, res: Response) => {
try { try {
let user = (req.query.user ?? '').toString(); let user = (req.query.user ?? '').toString();
let file = (req.query.file ?? '').toString(); let file = (req.query.file ?? '').toString();
let blockers = (req.query.blockers ?? '').toString() === '1'; let blockers = (req.query.blockers ?? '').toString() === '1';
let wahl = (req.query.wahl ?? '').toString(); let wahl = (req.query.wahl ?? '').toString();
let pflicht = (req.query.pflicht ?? '').toString(); let pflicht = (req.query.pflicht ?? '').toString();
const allowedCharsRegex: RegExp = /^[a-zA-Z0-9]+$/; const allowedCharsRegex: RegExp = /^[a-zA-Z0-9]+$/;
if (user === '' || file === '') { if (user === '' || file === '') {
res.status(400).send('Please at least provide user and file for RaPla!'); res.status(400).send('Please at least provide user and file for RaPla!');
return; return;
} else if (!allowedCharsRegex.test(user) || !allowedCharsRegex.test(file)) { } else if (!allowedCharsRegex.test(user) || !allowedCharsRegex.test(file)) {
res.status(400).send('Please provide a valid user and file!'); res.status(400).send('Please provide a valid user and file!');
return; return;
} }
let resultingFile = await icalgenerator.getiCalFile(user, file, blockers, wahl, pflicht); let resultingFile = await icalgenerator.getiCalFile(user, file, blockers, wahl, pflicht);
res.set({'Content-Disposition': 'attachment; filename=' + file + '.ics'}); res.set({'Content-Disposition': 'attachment; filename=' + file + '.ics'});
res.status(200).send(resultingFile); res.status(200).send(resultingFile);
} catch (e) { } catch (e: any) {
let errorGuid = Guid.create().toString(); let errorGuid = Guid.create().toString();
logger.error('Error handling a request: ' + e.message, {reference: errorGuid}); logger.error('Error handling a request: ' + e.message, {reference: errorGuid});
res.status(500).send({ res.status(500).send({
'status': 'PROCESSING_ERROR', 'status': 'PROCESSING_ERROR',
'message': 'Internal Server Error. Try again later.', 'message': 'Internal Server Error. Try again later.',
'reference': errorGuid 'reference': errorGuid
}); });
} }
}); });
@@ -1,218 +1,222 @@
const fetch = require('node-fetch'); const fetch = require('node-fetch');
export const getiCalFile = async (user: string, file: string, showBlockers: boolean, electiveModule: string, profileModule: string): Promise<string> => { export const getiCalFile = async (user: string, file: string, showBlockers: boolean, electiveModule: string, profileModule: string): Promise<string> => {
try { try {
let iCalFileContents = ''; let iCalFileContents = '';
let baseUrl = 'https://rapla.dhbw-karlsruhe.de/rapla?page=ical'; let baseUrl = 'https://rapla.dhbw-karlsruhe.de/rapla?page=ical';
baseUrl += '&user=' + user; baseUrl += '&user=' + user;
baseUrl += '&file=' + file; baseUrl += '&file=' + file;
const response = await fetch(baseUrl); const response = await fetch(baseUrl);
let body = await response.text(); let body = await response.text();
// Parse the ical file // Parse the ical file
let iCalFile = parseIcal(body); let iCalFile = parseIcal(body);
// Now remove unwanted shit from the iCal file // Now remove unwanted shit from the iCal file
if (!showBlockers) { if (!showBlockers) {
iCalFile = removeBlockers(iCalFile); iCalFile = removeBlockers(iCalFile);
} }
if (electiveModule !== '') { if (electiveModule !== '') {
iCalFile = removeElective(iCalFile, electiveModule); iCalFile = removeElective(iCalFile, electiveModule);
} }
if (profileModule !== '') { if (profileModule !== '') {
iCalFile = removeProfile(iCalFile, profileModule); iCalFile = removeProfile(iCalFile, profileModule);
} }
// Turn into one file again // Turn into one file again
let resultingFile = serializeIcal(iCalFile); let resultingFile = serializeIcal(iCalFile);
return resultingFile; return resultingFile;
} catch (err) { } catch (err) {
throw err; throw err;
} }
}; };
export const parseIcal = function (icalContents: string): iCalFile { export const parseIcal = function (icalContents: string): iCalFile {
const fileHeaderRegex: RegExp = /^BEGIN:VCALENDAR.*?BEGIN:VEVENT$/ms; const fileHeaderRegex: RegExp = /^BEGIN:VCALENDAR.*?BEGIN:VEVENT$/ms;
const eventRegex: RegExp = /^BEGIN:VEVENT.*?END:VEVENT$/msg; const eventRegex: RegExp = /^BEGIN:VEVENT.*?END:VEVENT$/msg;
let headerMatch = fileHeaderRegex.exec(icalContents); let headerMatch = fileHeaderRegex.exec(icalContents);
let header = ''; let header = '';
if (headerMatch) { if (headerMatch) {
header = headerMatch[0]; header = headerMatch[0];
} }
header = header.substr(0, header.lastIndexOf('\n') + 1); header = header.substr(0, header.lastIndexOf('\n') + 1);
let events: iCalEvent[] = []; let events: iCalEvent[] = [];
let match: any; let match: any;
while (match = eventRegex.exec(icalContents)) { while (match = eventRegex.exec(icalContents)) {
if (match) { if (match) {
events.push({ events.push({
content: match[0], content: match[0],
duration: getDuration(match[0]) duration: getDuration(match[0])
}); });
} }
} }
return { return {
head: header, head: header,
body: events body: events
}; };
}; };
export const getDuration = function (event: string): number { export const getDuration = function (event: string): number {
let startRegex: RegExp = /DTSTART.*?(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})Z?\r/gm; let startRegex: RegExp = /DTSTART.*?(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})Z?\r/gm;
let endRegex: RegExp = /DTEND.*?(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})Z?\r/gm; let endRegex: RegExp = /DTEND.*?(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})Z?\r/gm;
let startMatch = startRegex.exec(event); let startMatch = startRegex.exec(event);
let startDtYear = 0; let startDtYear = 0;
let startDtMonth = 0; let startDtMonth = 0;
let startDtDay = 0; let startDtDay = 0;
let startDtHour = 0; let startDtHour = 0;
let startDtMinute = 0; let startDtMinute = 0;
if (startMatch) { if (startMatch) {
startDtYear = parseInt(startMatch[1]); startDtYear = parseInt(startMatch[1]);
startDtMonth = parseInt(startMatch[2]); startDtMonth = parseInt(startMatch[2]);
startDtDay = parseInt(startMatch[3]); startDtDay = parseInt(startMatch[3]);
startDtHour = parseInt(startMatch[4]); startDtHour = parseInt(startMatch[4]);
startDtMinute = parseInt(startMatch[5]); startDtMinute = parseInt(startMatch[5]);
} }
let endMatch = endRegex.exec(event); let endMatch = endRegex.exec(event);
let endDtYear = 0; let endDtYear = 0;
let endDtMonth = 0; let endDtMonth = 0;
let endDtDay = 0; let endDtDay = 0;
let endDtHour = 0; let endDtHour = 0;
let endDtMinute = 0; let endDtMinute = 0;
if (endMatch) { if (endMatch) {
endDtYear = parseInt(endMatch[1]); endDtYear = parseInt(endMatch[1]);
endDtMonth = parseInt(endMatch[2]); endDtMonth = parseInt(endMatch[2]);
endDtDay = parseInt(endMatch[3]); endDtDay = parseInt(endMatch[3]);
endDtHour = parseInt(endMatch[4]); endDtHour = parseInt(endMatch[4]);
endDtMinute = parseInt(endMatch[5]); endDtMinute = parseInt(endMatch[5]);
} }
let startDt = new Date(startDtYear, startDtMonth - 1, startDtDay, startDtHour, startDtMinute); let startDt = new Date(startDtYear, startDtMonth - 1, startDtDay, startDtHour, startDtMinute);
let endDt = new Date(endDtYear, endDtMonth - 1, endDtDay, endDtHour, endDtMinute); let endDt = new Date(endDtYear, endDtMonth - 1, endDtDay, endDtHour, endDtMinute);
let hourDifference = endDt.getHours() - startDt.getHours(); let hourDifference = endDt.getHours() - startDt.getHours();
let minuteDifference = 0; let minuteDifference = 0;
if (hourDifference === 0) { if (hourDifference === 0) {
minuteDifference = endDt.getMinutes() - startDt.getMinutes(); minuteDifference = endDt.getMinutes() - startDt.getMinutes();
} }
return hourDifference + (minuteDifference / 60); return hourDifference + (minuteDifference / 60);
}; };
export const serializeIcal = function (ical: iCalFile): string { export const serializeIcal = function (ical: iCalFile): string {
let resString = ical.head; let resString = ical.head;
ical.body.forEach((event) => { ical.body.forEach((event) => {
resString += event.content + '\n'; resString += event.content + '\n';
}); });
resString += 'END:VCALENDAR\n'; resString += 'END:VCALENDAR\n';
return resString; return resString;
}; };
export const removeBlockers = function (ical: iCalFile): iCalFile { export const removeBlockers = function (ical: iCalFile): iCalFile {
let remainingEvents: iCalEvent[] = []; let remainingEvents: iCalEvent[] = [];
ical.body.forEach((event) => { ical.body.forEach((event) => {
if ( if (
!event.content.includes('SUMMARY:Beginn Theorie') !event.content.includes('SUMMARY:Beginn Theorie')
&& !event.content.includes('SUMMARY:Präsenz') && !event.content.includes('SUMMARY:Präsenz')
&& event.duration < 10 && event.duration < 10
&& event.duration > 0.25 && event.duration > 0.25
) { ) {
remainingEvents.push(event); remainingEvents.push(event);
} }
}); });
ical.body = remainingEvents; ical.body = remainingEvents;
return ical; return ical;
}; };
export const removeElective = function (ical: iCalFile, chosenElective: string): iCalFile { export const removeElective = function (ical: iCalFile, chosenElective: string): iCalFile {
let remainingEvents: iCalEvent[] = []; let remainingEvents: iCalEvent[] = [];
let electiveToRemove = [ let electiveToRemove = [
{name: 'ERP-Systeme'}, {name: 'ERP-Systeme'},
{name: 'Ethik für Informatiker'}, {name: 'Ethik für Informatiker'},
{name: 'Evolutionäre Algorithmen'}, {name: 'Evolutionäre Algorithmen'},
{name: 'Forensik'}, {name: 'Forensik'},
{name: 'Kryptographische Verfahren'}, {name: 'Kryptographische Verfahren'},
{name: 'Robotik'}, {name: 'Robotik'},
{name: 'Web-Services'}, {name: 'Web-Services'},
{name: 'High Performance Computing'} {name: 'High Performance Computing'},
]; {name: 'Digitale Audiosignalverarbeitung'},
electiveToRemove.splice(parseInt(chosenElective), 1); {name: 'Psychologische Grundlagen für Informatiker'},
{name: 'Erklärbare Künstliche Intelligenz'},
{name: 'Innovation Management'}
];
electiveToRemove.splice(parseInt(chosenElective), 1);
ical.body.forEach((event) => { ical.body.forEach((event) => {
let addEvent = true; let addEvent = true;
electiveToRemove.forEach((module) => { electiveToRemove.forEach((module) => {
if (event.content.includes(module.name)) { if (event.content.includes(module.name)) {
addEvent = false; addEvent = false;
} }
}); });
if (addEvent) { if (addEvent) {
remainingEvents.push(event); remainingEvents.push(event);
} }
}); });
ical.body = remainingEvents; ical.body = remainingEvents;
return ical; return ical;
}; };
export const removeProfile = function (ical: iCalFile, chosenProfile: string): iCalFile { export const removeProfile = function (ical: iCalFile, chosenProfile: string): iCalFile {
let remainingEvents: iCalEvent[] = []; let remainingEvents: iCalEvent[] = [];
let profileToRemove = [ let profileToRemove = [
{names: ['.Grundlagen der KI (KI und BV)', 'Bildverarbeitung (KI und BV)']}, {names: ['.Grundlagen der KI (KI und BV)', 'Bildverarbeitung (KI und BV)']},
{names: ['Bildverarbeitung', 'Computergraphik']}, {names: ['Bildverarbeitung', 'Computergraphik']},
{names: ['Interaktive Systeme', 'Grundlagen der KI']}, {names: ['Interaktive Systeme', 'Grundlagen der KI']},
{names: ['e Business', 'angewandtes Projektmanagement']}, {names: ['e Business', 'angewandtes Projektmanagement']},
{names: ['Kommunikations und Netztechnik II']} {names: ['Kommunikations und Netztechnik II']}
]; ];
profileToRemove.splice(parseInt(chosenProfile), 1); profileToRemove.splice(parseInt(chosenProfile), 1);
ical.body.forEach((event) => { ical.body.forEach((event) => {
let addEvent = true; let addEvent = true;
profileToRemove.forEach((module) => { profileToRemove.forEach((module) => {
module.names.forEach((name) => { module.names.forEach((name) => {
if (event.content.includes(name)) { if (event.content.includes(name)) {
addEvent = false; addEvent = false;
} }
}); });
}); });
if (addEvent) { if (addEvent) {
remainingEvents.push(event); remainingEvents.push(event);
} }
}); });
ical.body = remainingEvents; ical.body = remainingEvents;
return ical; return ical;
}; };
export interface iCalFile { export interface iCalFile {
head: string; head: string;
body: iCalEvent[]; body: iCalEvent[];
} }
export interface iCalEvent { export interface iCalEvent {
content: string; content: string;
duration: number; // Duration in hours duration: number; // Duration in hours
} }
@@ -0,0 +1,19 @@
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();
};
}
@@ -14,15 +14,15 @@ export const highlightMarkerRouter = express.Router();
highlightMarkerRouter.use('/addHighlight', addHighlightRouter); highlightMarkerRouter.use('/addHighlight', addHighlightRouter);
highlightMarkerRouter.get('/', async (req: Request, res: Response) => { highlightMarkerRouter.get('/', async (req: Request, res: Response) => {
try { try {
res.status(200).send('Pluto Development Twitch Highlight Marker API Endpoint'); res.status(200).send('Pluto Development Twitch Highlight Marker API Endpoint');
} catch (e) { } catch (e: any) {
let errorGuid = Guid.create().toString(); let errorGuid = Guid.create().toString();
logger.error('Error handling a request: ' + e.message, {reference: errorGuid}); logger.error('Error handling a request: ' + e.message, {reference: errorGuid});
res.status(500).send({ res.status(500).send({
'status': 'PROCESSING_ERROR', 'status': 'PROCESSING_ERROR',
'message': 'Internal Server Error. Try again later.', 'message': 'Internal Server Error. Try again later.',
'reference': errorGuid 'reference': errorGuid
}); });
} }
}); });
@@ -12,46 +12,46 @@ import {Guid} from 'guid-typescript';
export const addHighlightRouter = express.Router(); export const addHighlightRouter = express.Router();
addHighlightRouter.get('/', (req: Request, res: Response) => { addHighlightRouter.get('/', (req: Request, res: Response) => {
try { try {
res.status(200).send('GET endpoint not defined.'); res.status(200).send('GET endpoint not defined.');
} catch (e) { } catch (e: any) {
let errorGuid = Guid.create().toString(); let errorGuid = Guid.create().toString();
logger.error('Error handling a request: ' + e.message, {reference: errorGuid}); logger.error('Error handling a request: ' + e.message, {reference: errorGuid});
res.status(500).send({ res.status(500).send({
'status': 'PROCESSING_ERROR', 'status': 'PROCESSING_ERROR',
'message': 'Internal Server Error. Try again later.', 'message': 'Internal Server Error. Try again later.',
'reference': errorGuid 'reference': errorGuid
}); });
} }
}); });
addHighlightRouter.post('/', (req: Request, res: Response) => { addHighlightRouter.post('/', (req: Request, res: Response) => {
try { try {
// Check input params // Check input params
const body = req.body; const body = req.body;
if (body.access_key !== process.env.TWITCH_HIGHLIGHTS_ACCESS_KEY) { if (body.access_key !== process.env.TWITCH_HIGHLIGHTS_ACCESS_KEY) {
// Unauthorized, return error // Unauthorized, return error
res.type('application/json'); res.type('application/json');
res.status(403).send({'status': 'error', 'description': 'Unauthorized.'}); res.status(403).send({'status': 'error', 'description': 'Unauthorized.'});
} else if (!body.streamer || !body.stream_id || !body.stream_game || !body.timestamp || !body.description || !body.username) { } else if (!body.streamer || !body.stream_id || !body.stream_game || !body.timestamp || !body.description || !body.username) {
// Missing params, return error // Missing params, return error
res.type('application/json'); res.type('application/json');
res.status(400).send({'status': 'error', 'description': 'Missing parameters.'}); res.status(400).send({'status': 'error', 'description': 'Missing parameters.'});
} else { } else {
// Everything fine, return success // Everything fine, return success
AddHighlightService.createHighlightEntry(body); AddHighlightService.createHighlightEntry(body);
res.type('application/json'); res.type('application/json');
res.status(200).send({'status': 'success', 'description': ''}); res.status(200).send({'status': 'success', 'description': ''});
} }
} catch (e) { } catch (e: any) {
let errorGuid = Guid.create().toString(); let errorGuid = Guid.create().toString();
logger.error('Error handling a request: ' + e.message, {reference: errorGuid}); logger.error('Error handling a request: ' + e.message, {reference: errorGuid});
res.status(500).send({ res.status(500).send({
'status': 'PROCESSING_ERROR', 'status': 'PROCESSING_ERROR',
'message': 'Internal Server Error. Try again later.', 'message': 'Internal Server Error. Try again later.',
'reference': errorGuid 'reference': errorGuid
}); });
} }
}); });
@@ -1,42 +1,31 @@
import * as dotenv from 'dotenv'; import * as dotenv from 'dotenv';
import {HighlightMarkerDB} from '../HighlightMarker.db';
dotenv.config(); 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 * Creates a new highlight entry in SQL
* @param req_body The request body * @param req_body The request body
*/ */
export const createHighlightEntry = async (req_body: any) => { export const createHighlightEntry = async (req_body: any) => {
let conn; let conn = await HighlightMarkerDB.getConnection();
try { 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;
const streamers = await conn.query('SELECT streamer_id FROM streamers WHERE username = ?', req_body.streamer); for (let row in streamers) {
let streamer_id: number = -1; if (row !== 'meta') {
streamer_id = streamers[row].streamer_id;
}
}
for (let row in streamers) { const params = [streamer_id, req_body.stream_id, req_body.description, req_body.timestamp, req_body.username, req_body.stream_game];
if (row !== 'meta') {
streamer_id = streamers[row].streamer_id;
}
}
const params = [streamer_id, req_body.stream_id, req_body.description, req_body.timestamp, req_body.username, req_body.stream_game]; const rows = await conn.query('INSERT INTO highlights (streamer_id, stream_id, description, stream_timestamp, issuing_user, game) VALUES (?, ?, ?, ?, ?, ?)', params);
} catch (err) {
const rows = await conn.query('INSERT INTO highlights (streamer_id, stream_id, description, stream_timestamp, issuing_user, game) VALUES (?, ?, ?, ?, ?, ?)', params); throw err;
} catch (err) { } finally {
throw err; // Return connection
} finally { await conn.end();
if (conn) { }
conn.end();
}
}
}; };

Some files were not shown because too many files have changed in this diff Show More