Compare commits

..

No commits in common. "b3abeaa264d43e374c346a9b112cc074fc95edde" and "ec533394ce481953baa0ab54965d6bd8d0334993" have entirely different histories.

25 changed files with 582 additions and 187 deletions

2
app.ts
View File

@ -37,7 +37,7 @@ app.use(
swaggerUi.serve, swaggerUi.serve,
swaggerUi.setup(undefined, { swaggerUi.setup(undefined, {
swaggerOptions: { swaggerOptions: {
url: '/swagger.json' url: '/public/swagger.json'
} }
}) })
); );

View File

@ -1,19 +0,0 @@
import * as dotenv from 'dotenv';
const mariadb = require('mariadb');
dotenv.config();
export namespace BetterzonDB {
const pool = mariadb.createPool({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.BETTERZON_DATABASE,
connectionLimit: 5
});
export function getConnection() {
return pool;
}
}

View File

@ -34,7 +34,7 @@ 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 Betterzon API Endpoint'); res.status(200).send('Pluto Development PartyPlaner API Endpoint V2');
} catch (e) { } catch (e) {
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});

View File

@ -1,10 +1,18 @@
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
*/ */
@ -18,9 +26,10 @@ dotenv.config();
* 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 = BetterzonDB.getConnection(); let conn;
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') {
@ -38,6 +47,10 @@ export const findAll = async (): Promise<Categories> => {
} catch (err) { } catch (err) {
throw err; throw err;
} finally {
if (conn) {
conn.end();
}
} }
return categRows; return categRows;
@ -48,9 +61,10 @@ 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 = BetterzonDB.getConnection(); let conn;
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') {
@ -60,6 +74,10 @@ export const find = async (id: number): Promise<Category> => {
} catch (err) { } catch (err) {
throw err; throw err;
} finally {
if (conn) {
conn.end();
}
} }
return categ; return categ;
@ -70,9 +88,10 @@ 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 = BetterzonDB.getConnection(); let conn;
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) {
@ -83,6 +102,10 @@ export const findBySearchTerm = async (term: string): Promise<Categories> => {
} catch (err) { } catch (err) {
throw err; throw err;
} finally {
if (conn) {
conn.end();
}
} }
return categRows; return categRows;

View File

@ -1,10 +1,18 @@
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
*/ */
@ -18,9 +26,10 @@ dotenv.config();
* 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 = BetterzonDB.getConnection(); let conn;
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') {
@ -30,6 +39,10 @@ export const findAll = async (): Promise<Contact_Persons> => {
} catch (err) { } catch (err) {
throw err; throw err;
} finally {
if (conn) {
conn.end();
}
} }
return contRows; return contRows;
@ -40,9 +53,10 @@ 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 = BetterzonDB.getConnection(); let conn;
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') {
@ -52,6 +66,10 @@ export const find = async (id: number): Promise<Contact_Person> => {
} catch (err) { } catch (err) {
throw err; throw err;
} finally {
if (conn) {
conn.end();
}
} }
return cont; return cont;
@ -62,9 +80,10 @@ 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 = BetterzonDB.getConnection(); let conn;
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') {
@ -74,6 +93,10 @@ export const findByVendor = async (id: number): Promise<Contact_Persons> => {
} catch (err) { } catch (err) {
throw err; throw err;
} finally {
if (conn) {
conn.end();
}
} }
return contRows; return contRows;
@ -90,8 +113,10 @@ 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 = BetterzonDB.getConnection(); let conn;
try { try {
conn = await pool.getConnection();
// Check if the user is authorized to manage the requested vendor // 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]); 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) { if (user_vendor_rows.length !== 1) {
@ -105,6 +130,10 @@ export const createContactEntry = async (user_id: number, vendor_id: number, fir
return res.affectedRows === 1; return res.affectedRows === 1;
} catch (err) { } catch (err) {
throw err; throw err;
} finally {
if (conn) {
conn.end();
}
} }
}; };
@ -120,8 +149,10 @@ 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 = BetterzonDB.getConnection(); let conn;
try { try {
conn = await pool.getConnection();
// Check if the user is authorized to manage the requested vendor // 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]); 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) { if (user_vendor_rows.length !== 1) {
@ -135,5 +166,9 @@ export const updateContactEntry = async (user_id: number, contact_person_id: num
return res.affectedRows === 1; return res.affectedRows === 1;
} catch (err) { } catch (err) {
throw err; throw err;
} finally {
if (conn) {
conn.end();
}
} }
}; };

View File

@ -1,9 +1,17 @@
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
*/ */
@ -17,8 +25,10 @@ dotenv.config();
* 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 = BetterzonDB.getConnection(); let conn;
try { try {
conn = await pool.getConnection();
// Get the current crawling process // Get the current crawling process
let process_info = { let process_info = {
process_id: -1, process_id: -1,
@ -55,5 +65,9 @@ export const getCurrent = async (): Promise<Crawling_Status> => {
} catch (err) { } catch (err) {
throw err; throw err;
} finally {
if (conn) {
conn.end();
}
} }
}; };

View File

@ -1,9 +1,17 @@
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
*/ */
@ -19,13 +27,18 @@ dotenv.config();
* @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 = BetterzonDB.getConnection(); let conn;
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 {
if (conn) {
conn.end();
}
} }
}; };
@ -34,9 +47,10 @@ 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 = BetterzonDB.getConnection(); let conn;
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') {
@ -47,6 +61,10 @@ export const getFavoriteShops = async (user_id: number): Promise<FavoriteShops>
return shops; return shops;
} catch (err) { } catch (err) {
throw err; throw err;
} finally {
if (conn) {
conn.end();
}
} }
}; };
@ -56,12 +74,17 @@ 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 = BetterzonDB.getConnection(); let conn;
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 {
if (conn) {
conn.end();
}
} }
}; };

View File

@ -1,10 +1,18 @@
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
*/ */
@ -18,9 +26,10 @@ dotenv.config();
* 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 = BetterzonDB.getConnection(); let conn;
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') {
@ -38,6 +47,10 @@ export const findAll = async (): Promise<Manufacturers> => {
} catch (err) { } catch (err) {
throw err; throw err;
} finally {
if (conn) {
conn.end();
}
} }
return manRows; return manRows;
@ -48,9 +61,10 @@ 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 = BetterzonDB.getConnection(); let conn;
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') {
@ -60,6 +74,10 @@ export const find = async (id: number): Promise<Manufacturer> => {
} catch (err) { } catch (err) {
throw err; throw err;
} finally {
if (conn) {
conn.end();
}
} }
return man; return man;
@ -70,9 +88,10 @@ 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 = BetterzonDB.getConnection(); let conn;
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) {
@ -83,6 +102,10 @@ export const findBySearchTerm = async (term: string): Promise<Manufacturers> =>
} catch (err) { } catch (err) {
throw err; throw err;
} finally {
if (conn) {
conn.end();
}
} }
return manRows; return manRows;

View File

@ -1,9 +1,17 @@
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
*/ */
@ -20,13 +28,18 @@ dotenv.config();
* @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 = BetterzonDB.getConnection(); let conn;
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 {
if (conn) {
conn.end();
}
} }
}; };
@ -35,9 +48,10 @@ 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 = BetterzonDB.getConnection(); let conn;
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') {
@ -48,6 +62,10 @@ export const getPriceAlarms = async (user_id: number): Promise<PriceAlarms> => {
return priceAlarms; return priceAlarms;
} catch (err) { } catch (err) {
throw err; throw err;
} finally {
if (conn) {
conn.end();
}
} }
}; };
@ -58,13 +76,18 @@ 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 = BetterzonDB.getConnection(); let conn;
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 {
if (conn) {
conn.end();
}
} }
}; };
@ -74,12 +97,17 @@ export const updatePriceAlarm = async (alarm_id: number, user_id: number, define
* @param user_id The id of the user that wants to update the price alarm * @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 = BetterzonDB.getConnection(); let conn;
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 {
if (conn) {
conn.end();
}
} }
}; };

View File

@ -1,10 +1,18 @@
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
*/ */
@ -18,9 +26,10 @@ dotenv.config();
* 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 = BetterzonDB.getConnection(); let conn;
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') {
@ -44,6 +53,10 @@ export const findAll = async (): Promise<Prices> => {
} catch (err) { } catch (err) {
throw err; throw err;
} finally {
if (conn) {
conn.end();
}
} }
return priceRows; return priceRows;
@ -54,9 +67,10 @@ 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 = BetterzonDB.getConnection(); let conn;
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') {
@ -66,6 +80,10 @@ export const find = async (id: number): Promise<Price> => {
} catch (err) { } catch (err) {
throw err; throw err;
} finally {
if (conn) {
conn.end();
}
} }
return price; return price;
@ -76,9 +94,10 @@ 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 = BetterzonDB.getConnection(); let conn;
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') {
@ -88,6 +107,10 @@ export const findByProduct = async (product: number): Promise<Prices> => {
} catch (err) { } catch (err) {
throw err; throw err;
} finally {
if (conn) {
conn.end();
}
} }
return priceRows; return priceRows;
@ -102,9 +125,10 @@ 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 = BetterzonDB.getConnection(); let conn;
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
@ -138,6 +162,10 @@ export const findByType = async (product: string, type: string): Promise<Prices>
} catch (err) { } catch (err) {
throw err; throw err;
} finally {
if (conn) {
conn.end();
}
} }
return priceRows; return priceRows;
@ -153,9 +181,10 @@ 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 = BetterzonDB.getConnection(); let conn;
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
@ -176,6 +205,10 @@ export const findByVendor = async (product: string, vendor: string, type: string
} catch (err) { } catch (err) {
throw err; throw err;
} finally {
if (conn) {
conn.end();
}
} }
return priceRows; return priceRows;
@ -187,9 +220,11 @@ 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 = BetterzonDB.getConnection(); let conn;
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 // Get newest prices for every product at every vendor
@ -268,6 +303,10 @@ export const getBestDeals = async (amount: number): Promise<Prices> => {
} catch (err) { } catch (err) {
console.log(err); console.log(err);
throw err; throw err;
} finally {
if (conn) {
conn.end();
}
} }
return priceRows; return priceRows;
@ -278,9 +317,11 @@ 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 = BetterzonDB.getConnection(); let conn;
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 // Get newest prices for every given product at every vendor
@ -325,14 +366,20 @@ export const findListByProducts = async (productIds: [number]): Promise<Prices>
}); });
} catch (err) { } catch (err) {
throw err; throw err;
} finally {
if (conn) {
conn.end();
}
} }
return priceRows; 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 = BetterzonDB.getConnection(); let conn;
try { try {
conn = await pool.getConnection();
// Check if the user is authorized to manage the requested vendor // 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]); 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) { if (user_vendor_rows.length !== 1) {
@ -346,5 +393,9 @@ export const createPriceEntry = async (user_id: number, vendor_id: number, produ
return res.affectedRows === 1; return res.affectedRows === 1;
} catch (err) { } catch (err) {
throw err; throw err;
} finally {
if (conn) {
conn.end();
}
} }
}; };

View File

@ -2,10 +2,18 @@ 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
*/ */
@ -19,9 +27,10 @@ dotenv.config();
* 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 = BetterzonDB.getConnection(); let conn;
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') {
@ -59,6 +68,10 @@ export const findAll = async (): Promise<Products> => {
} catch (err) { } catch (err) {
throw err; throw err;
} finally {
if (conn) {
conn.end();
}
} }
return prodRows; return prodRows;
@ -69,9 +82,10 @@ 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 = BetterzonDB.getConnection(); let conn;
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') {
@ -81,6 +95,10 @@ export const find = async (id: number): Promise<Product> => {
} catch (err) { } catch (err) {
throw err; throw err;
} finally {
if (conn) {
conn.end();
}
} }
return prod; return prod;
@ -91,9 +109,10 @@ 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 = BetterzonDB.getConnection(); let conn;
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) {
@ -105,6 +124,10 @@ export const findBySearchTerm = async (term: string): Promise<Products> => {
} catch (err) { } catch (err) {
console.log(err); console.log(err);
throw err; throw err;
} finally {
if (conn) {
conn.end();
}
} }
return prodRows; return prodRows;
@ -115,9 +138,10 @@ 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 = BetterzonDB.getConnection(); let conn;
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') {
@ -127,6 +151,10 @@ export const findList = async (ids: [number]): Promise<Products> => {
} catch (err) { } catch (err) {
throw err; throw err;
} finally {
if (conn) {
conn.end();
}
} }
return prodRows; return prodRows;
@ -137,9 +165,11 @@ 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 = BetterzonDB.getConnection(); let conn;
let prodRows = []; let prodRows = [];
try { try {
conn = await pool.getConnection();
// Get the relevant product ids // Get the relevant product ids
let relevant_prod_ids = []; let relevant_prod_ids = [];
const relevantProds = await conn.query('SELECT product_id FROM prices WHERE vendor_id = ? GROUP BY product_id', id); const relevantProds = await conn.query('SELECT product_id FROM prices WHERE vendor_id = ? GROUP BY product_id', id);
@ -159,6 +189,10 @@ export const findByVendor = async (id: number): Promise<Products> => {
} catch (err) { } catch (err) {
throw err; throw err;
} finally {
if (conn) {
conn.end();
}
} }
return prodRows; return prodRows;

View File

@ -3,11 +3,19 @@ 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
*/ */
@ -21,7 +29,7 @@ dotenv.config();
* 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 = BetterzonDB.getConnection(); let conn;
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);
@ -29,6 +37,7 @@ export const createUser = async (username: string, password: string, email: stri
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();
@ -63,6 +72,10 @@ export const createUser = async (username: string, password: string, email: stri
} catch (err) { } catch (err) {
throw err; throw err;
} finally {
if (conn) {
conn.end();
}
} }
return {} as Session; return {} as Session;
@ -73,9 +86,10 @@ 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 = BetterzonDB.getConnection(); let conn;
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 = '';
@ -125,6 +139,10 @@ export const login = async (username: string, password: string, ip: string): Pro
} catch (err) { } catch (err) {
throw err; throw err;
} finally {
if (conn) {
conn.end();
}
} }
return {} as Session; return {} as Session;
@ -134,9 +152,10 @@ export const login = async (username: string, password: string, ip: string): Pro
* 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 = BetterzonDB.getConnection(); let conn;
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 = '';
@ -202,6 +221,10 @@ export const checkSession = async (sessionId: string, sessionKey: string, ip: st
} catch (err) { } catch (err) {
throw err; throw err;
} finally {
if (conn) {
conn.end();
}
} }
}; };
@ -234,9 +257,10 @@ 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 = BetterzonDB.getConnection(); let conn;
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);
@ -282,5 +306,9 @@ export const checkUsernameAndEmail = async (username: string, email: string): Pr
} catch (err) { } catch (err) {
throw err; throw err;
} finally {
if (conn) {
conn.end();
}
} }
}; };

View File

@ -1,10 +1,18 @@
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
*/ */
@ -18,9 +26,10 @@ dotenv.config();
* 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 = BetterzonDB.getConnection(); let conn;
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') {
@ -50,6 +59,10 @@ export const findAll = async (): Promise<Vendors> => {
} catch (err) { } catch (err) {
throw err; throw err;
} finally {
if (conn) {
conn.end();
}
} }
return vendorRows; return vendorRows;
@ -60,9 +73,10 @@ 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 = BetterzonDB.getConnection(); let conn;
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') {
@ -72,6 +86,10 @@ export const find = async (id: number): Promise<Vendor> => {
} catch (err) { } catch (err) {
throw err; throw err;
} finally {
if (conn) {
conn.end();
}
} }
return vendor; return vendor;
@ -82,9 +100,10 @@ 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 = BetterzonDB.getConnection(); let conn;
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) {
@ -95,6 +114,10 @@ export const findBySearchTerm = async (term: string): Promise<Vendors> => {
} catch (err) { } catch (err) {
throw err; throw err;
} finally {
if (conn) {
conn.end();
}
} }
return vendorRows; return vendorRows;
@ -105,9 +128,10 @@ 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 = BetterzonDB.getConnection(); let conn;
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') {
@ -117,6 +141,10 @@ export const getManagedShops = async (user_id: number): Promise<Vendors> => {
} catch (err) { } catch (err) {
throw err; throw err;
} finally {
if (conn) {
conn.end();
}
} }
return vendorRows; return vendorRows;
@ -129,8 +157,10 @@ export const getManagedShops = async (user_id: number): Promise<Vendors> => {
* @param product_id The product id of the product to deactivate the listing for * @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 = BetterzonDB.getConnection(); let conn;
try { try {
conn = await pool.getConnection();
// Check if the user is authorized to manage the requested vendor // 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]); 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) { if (user_vendor_rows.length !== 1) {
@ -142,6 +172,10 @@ export const deactivateListing = async (user_id: number, vendor_id: number, prod
return status.affectedRows > 0; return status.affectedRows > 0;
} catch (err) { } catch (err) {
throw err; throw err;
} finally {
if (conn) {
conn.end();
}
} }
return false; return false;
@ -154,8 +188,10 @@ 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 = BetterzonDB.getConnection(); let conn;
try { try {
conn = await pool.getConnection();
// Check if the user is authorized to manage the requested vendor // 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]); 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) { if (user_vendor_rows.length !== 1) {
@ -168,6 +204,10 @@ export const setShopStatus = async (user_id: number, vendor_id: number, isActive
return status.affectedRows > 0; return status.affectedRows > 0;
} catch (err) { } catch (err) {
throw err; throw err;
} finally {
if (conn) {
conn.end();
}
} }
return false; return false;

View File

@ -1,19 +0,0 @@
import * as dotenv from 'dotenv';
const mariadb = require('mariadb');
dotenv.config();
export namespace RaPlaChangesDB {
const pool = mariadb.createPool({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.RAPLACHANGES_DATABASE,
connectionLimit: 5
});
export function getConnection() {
return pool;
}
}

View File

@ -1,13 +1,23 @@
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 = RaPlaChangesDB.getConnection(); let conn;
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[] = []; let relevantEventIds: string[] = [];
@ -68,12 +78,18 @@ export const getChanges = async (course: string, week: string): Promise<Event[]>
return Array.from(eventsMap.values()) as Event[]; return Array.from(eventsMap.values()) as Event[];
} catch (err) { } catch (err) {
throw err; 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 = RaPlaChangesDB.getConnection(); let conn;
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();
@ -123,5 +139,9 @@ export const getEventById = async (course: string, id: string): Promise<Event> =
return Array.from(eventsMap.values())[0]; return Array.from(eventsMap.values())[0];
} catch (err) { } catch (err) {
throw err; throw err;
} finally {
if (conn) {
conn.end();
}
} }
}; };

View File

@ -1,29 +0,0 @@
import * as dotenv from 'dotenv';
const mariadb = require('mariadb');
dotenv.config();
export namespace PartyPlanerDB {
const prod_pool = mariadb.createPool({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.PARTYPLANER_PROD_DATABASE,
connectionLimit: 5
});
const dev_pool = mariadb.createPool({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.PARTYPLANER_DEV_DATABASE,
connectionLimit: 5
});
export function getConnection(useDev: boolean = false) {
if (useDev) {
return dev_pool;
}
return prod_pool;
}
}

View File

@ -1,9 +1,24 @@
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
@ -11,8 +26,14 @@ dotenv.config();
* @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 = PartyPlanerDB.getConnection(useDev); let conn;
try { try {
if (useDev) {
conn = await dev_pool.getConnection();
} else {
conn = await prod_pool.getConnection();
}
let eventRows = await conn.query('SELECT event_id, name, description, takes_place_date, registration_until_date, max_participants FROM events WHERE creator_id = ?', userId); let 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 eventsMap = new Map<string, Event>();
@ -69,5 +90,9 @@ export const getEventData = async (useDev: boolean, userId: string): Promise<Eve
return eventsList; return eventsList;
} catch (err) { } catch (err) {
throw err; throw err;
} finally {
if (conn) {
conn.end();
}
} }
}; };

View File

@ -1,9 +1,24 @@
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
@ -11,8 +26,14 @@ dotenv.config();
* @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 = PartyPlanerDB.getConnection(useDev); let conn;
try { try {
if (useDev) {
conn = await dev_pool.getConnection();
} else {
conn = await prod_pool.getConnection();
}
let rows = await conn.query('SELECT f.friendship_id, f.friend_id, u.first_name as friend_first_name, u.last_name as friend_last_name, u.username as friend_username FROM friendships f LEFT OUTER JOIN users u ON f.friend_id = u.user_id WHERE f.user_id = ?', userId); let 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[] = [];
@ -30,5 +51,9 @@ export const getFriendshipData = async (useDev: boolean, userId: string): Promis
return friends; return friends;
} catch (err) { } catch (err) {
throw err; throw err;
} finally {
if (conn) {
conn.end();
}
} }
}; };

View File

@ -1,9 +1,24 @@
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
@ -11,8 +26,14 @@ dotenv.config();
* @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 = PartyPlanerDB.getConnection(useDev); let conn;
try { try {
if (useDev) {
conn = await dev_pool.getConnection();
} else {
conn = await prod_pool.getConnection();
}
let rows = await conn.query('SELECT i.invite_id, i.valid_until, i.already_used, i.invite_key, e.name as event_name, e.description as event_description, e.takes_place_date, e.registration_until_date, e.max_participants, e.creator_id, u.first_name, u.last_name FROM invitations i LEFT OUTER JOIN events e ON e.event_id = i.event_id LEFT OUTER JOIN users u ON u.user_id = e.creator_id WHERE i.user_id = ?', userId); let 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[] = [];
@ -37,5 +58,9 @@ export const getInvitesData = async (useDev: boolean, userId: string): Promise<R
return invites; return invites;
} catch (err) { } catch (err) {
throw err; throw err;
} finally {
if (conn) {
conn.end();
}
} }
}; };

View File

@ -1,9 +1,24 @@
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
@ -11,8 +26,14 @@ dotenv.config();
* @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 = PartyPlanerDB.getConnection(useDev); let conn;
try { try {
if (useDev) {
conn = await dev_pool.getConnection();
} else {
conn = await prod_pool.getConnection();
}
let rows = await conn.query('SELECT session_id, type, last_login, last_ip FROM sessions WHERE user_id = ? AND valid_until > NOW()', userId); let 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[] = [];
@ -29,5 +50,9 @@ export const getSessionData = async (useDev: boolean, userId: string): Promise<S
return sessions; return sessions;
} catch (err) { } catch (err) {
throw err; throw err;
} finally {
if (conn) {
conn.end();
}
} }
}; };

View File

@ -4,10 +4,25 @@ 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
@ -15,8 +30,14 @@ dotenv.config();
* @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 = PartyPlanerDB.getConnection(useDev); let conn;
try { try {
if (useDev) {
conn = await dev_pool.getConnection();
} else {
conn = await prod_pool.getConnection();
}
let rows = await conn.query('SELECT username, email, first_name, last_Name, last_login, email_is_verified, is_premium_user FROM users WHERE user_id = ?', userId); let 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;
@ -36,6 +57,10 @@ export const getUserData = async (useDev: boolean, userId: string): Promise<User
return user; return user;
} catch (err) { } catch (err) {
throw err; throw err;
} finally {
if (conn) {
conn.end();
}
} }
}; };
@ -45,8 +70,14 @@ 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 = PartyPlanerDB.getConnection(useDev); let conn;
try { try {
if (useDev) {
conn = await dev_pool.getConnection();
} else {
conn = await prod_pool.getConnection();
}
const rows = await conn.query('SELECT username, email FROM users'); const rows = await conn.query('SELECT username, email FROM users');
let usernames: string[] = []; let usernames: string[] = [];
@ -63,6 +94,10 @@ export const getExistingUsernamesAndEmails = async (useDev: boolean): Promise<an
}; };
} catch (err) { } catch (err) {
throw err; throw err;
} finally {
if (conn) {
conn.end();
}
} }
}; };
@ -78,8 +113,14 @@ 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 = PartyPlanerDB.getConnection(useDev); let conn;
try { try {
if (useDev) {
conn = await dev_pool.getConnection();
} else {
conn = await prod_pool.getConnection();
}
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);
@ -125,6 +166,10 @@ export const registerUser = async (useDev: boolean, username: string, email: str
}; };
} catch (err) { } catch (err) {
throw err; throw err;
} finally {
if (conn) {
conn.end();
}
} }
}; };
@ -138,8 +183,14 @@ 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 = PartyPlanerDB.getConnection(useDev); let conn;
try { try {
if (useDev) {
conn = await dev_pool.getConnection();
} else {
conn = await prod_pool.getConnection();
}
let query_result; let query_result;
// Get the saved hash // Get the saved hash
@ -197,6 +248,10 @@ export const loginUser = async (useDev: boolean, username: string, email: string
} catch (err) { } catch (err) {
throw err; throw err;
} finally {
if (conn) {
conn.end();
}
} }
}; };
@ -207,8 +262,13 @@ 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 = PartyPlanerDB.getConnection(useDev); let conn;
try { try {
if (useDev) {
conn = await dev_pool.getConnection();
} else {
conn = await prod_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);
@ -254,12 +314,22 @@ export const checkUsernameAndEmail = async (useDev: boolean, username: string, e
} catch (err) { } catch (err) {
throw err; throw err;
} finally {
if (conn) {
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 = PartyPlanerDB.getConnection(useDev); let conn;
try { try {
if (useDev) {
conn = await dev_pool.getConnection();
} else {
conn = await prod_pool.getConnection();
}
let rows = await conn.query('SELECT session_key_hash FROM sessions WHERE user_id = ? AND session_id = ?', [userId, sessionId]); let rows = await conn.query('SELECT session_key_hash FROM sessions WHERE user_id = ? AND session_id = ?', [userId, sessionId]);
let savedHash = ''; let savedHash = '';
@ -270,5 +340,9 @@ export const checkSession = async (useDev: boolean, userId: string, sessionId: s
return bcrypt.compareSync(sessionKey, savedHash); return bcrypt.compareSync(sessionKey, savedHash);
} catch (err) { } catch (err) {
throw err; throw err;
} finally {
if (conn) {
conn.end();
}
} }
}; };

View File

@ -1,19 +0,0 @@
import * as dotenv from 'dotenv';
const mariadb = require('mariadb');
dotenv.config();
export namespace HighlightMarkerDB {
const pool = mariadb.createPool({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.BETTERZON_DATABASE,
connectionLimit: 5
});
export function getConnection() {
return pool;
}
}

View File

@ -1,15 +1,25 @@
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 = HighlightMarkerDB.getConnection(); let conn;
try { try {
conn = await pool.getConnection();
const streamers = await conn.query('SELECT streamer_id FROM streamers WHERE username = ?', req_body.streamer); const streamers = await conn.query('SELECT streamer_id FROM streamers WHERE username = ?', req_body.streamer);
let streamer_id: number = -1; let streamer_id: number = -1;
@ -24,5 +34,9 @@ export const createHighlightEntry = async (req_body: any) => {
const rows = await conn.query('INSERT INTO highlights (streamer_id, stream_id, description, stream_timestamp, issuing_user, game) VALUES (?, ?, ?, ?, ?, ?)', params); const rows = await conn.query('INSERT INTO highlights (streamer_id, stream_id, description, stream_timestamp, issuing_user, game) VALUES (?, ?, ?, ?, ?, ?)', params);
} catch (err) { } catch (err) {
throw err; throw err;
} finally {
if (conn) {
conn.end();
}
} }
}; };

View File

@ -1,26 +0,0 @@
{
"components": {
"examples": {},
"headers": {},
"parameters": {},
"requestBodies": {},
"responses": {},
"schemas": {},
"securitySchemes": {}
},
"info": {
"title": "plutodev_express_api",
"version": "1.0.0",
"license": {
"name": "ISC"
},
"contact": {}
},
"openapi": "3.0.0",
"paths": {},
"servers": [
{
"url": "/"
}
]
}

View File

@ -2,7 +2,7 @@
"entryFile": "app.ts", "entryFile": "app.ts",
"noImplicitAdditionalProperties": "throw-on-extras", "noImplicitAdditionalProperties": "throw-on-extras",
"spec": { "spec": {
"outputDirectory": ".", "outputDirectory": "public",
"specVersion": 3 "specVersion": 3
} }
} }