Compare commits

..
Author SHA1 Message Date
PaddyandClaude Opus 5.5 095815e0f3 Deploy with Gitea Actions instead of Jenkins on Node 26, drop SonarQube
Test and deploy / test-and-deploy (pull_request) Successful in 30s
One job: npm ci, tsc --noEmit, npm test on Node 26; on pushes to master
it builds, prunes dev dependencies and rsyncs dist/, src/ (Swagger reads
it) and node_modules/ over SSH as plesk-plutodev, then restarts Passenger
and smoke-tests /docs/. The server's .env, logs/, tmp/ and public/ are
never touched - .env is no longer generated by CI but kept on the server.

Plesk moves from Node 12.22.12 to 26 with this; the bundle built on 26
also starts on 12, so the order of deploy and Plesk switch doesn't
matter. SonarQube leftovers are gone.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 13:03:00 +01:00
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
69 changed files with 10128 additions and 1004 deletions

No files matched your search

+106
View File
@@ -0,0 +1,106 @@
# Tests every push and pull request; deploys pushes to master to the Plesk server (api.plutodev.de).
# Setup and what the deploy may touch: DEPLOYMENT.md.
#
# Same pattern as the Nachklang API (git.plutodev.de/Nachklang/API): build here, deliver over SSH as
# the Plesk subscription user (plesk-plutodev), restart Passenger. The app folder also holds things
# the deploy must never touch (.env with the secrets, logs/, tmp/), so only the app's own folders
# are synced with --delete and nothing is deleted at the top level.
name: Test and deploy
on:
push:
branches: [master]
pull_request:
jobs:
# One job, not test + deploy: every job starts in a fresh container, so two jobs meant checking out,
# setting up Node and running `npm ci` twice (~2 min each, 2026-11-08). The deploy steps only run
# for pushes to master; on pull requests the job ends after the tests. The condition is spelled out
# on every deploy step rather than stored in an env flag: a flag compared as a string ('true') would
# skip the deploy silently - and green - if the runner ever rendered the boolean differently.
test-and-deploy:
runs-on: ubuntu-latest
env:
DEPLOY_HOST: ${{ vars.DEPLOY_HOST }}
DEPLOY_PORT: ${{ vars.DEPLOY_PORT }}
DEPLOY_USER: ${{ vars.DEPLOY_USER }}
DEPLOY_PATH: ${{ vars.DEPLOY_PATH }}
# Absolute on purpose: rsync passes its -e string to ssh without a shell, and ssh expands "~"
# from the passwd entry, not $HOME (found in the Nachklang calendar migration, 2026-11-08).
SSH_DIR: /tmp/deploy-ssh
steps:
- uses: actions/checkout@v4
# .nvmrc = 26, the Node version Plesk runs this app with from the switchover on (it was
# 12.22.12 until 2026-11-16). Build and test with the same one.
- uses: actions/setup-node@v4
with:
node-version-file: .nvmrc
- run: npm ci
- run: npx tsc --noEmit
- run: npm test
- name: Build
if: github.event_name == 'push' && github.ref == 'refs/heads/master'
run: npm run build
# Only runtime dependencies go to the server (no typescript, jest, ...).
- name: Prune dev dependencies
if: github.event_name == 'push' && github.ref == 'refs/heads/master'
run: npm prune --omit=dev
- name: SSH setup
if: github.event_name == 'push' && github.ref == 'refs/heads/master'
env:
DEPLOY_SSH_KEY: ${{ secrets.DEPLOY_SSH_KEY }}
DEPLOY_KNOWN_HOSTS: ${{ secrets.DEPLOY_KNOWN_HOSTS }}
run: |
test -n "$DEPLOY_HOST" && test -n "$DEPLOY_USER" && test -n "$DEPLOY_PATH"
if ! command -v rsync >/dev/null 2>&1 || ! command -v ssh >/dev/null 2>&1; then
apt-get update && apt-get install -y --no-install-recommends rsync openssh-client
fi
install -m 700 -d "$SSH_DIR"
printf '%s\n' "$DEPLOY_SSH_KEY" > "$SSH_DIR/key"
chmod 600 "$SSH_DIR/key"
# Pinned host key, never trust-on-first-use.
printf '%s\n' "$DEPLOY_KNOWN_HOSTS" > "$SSH_DIR/known_hosts"
- name: Upload
if: github.event_name == 'push' && github.ref == 'refs/heads/master'
run: |
rsh="ssh -p ${DEPLOY_PORT:-22} -i $SSH_DIR/key -o UserKnownHostsFile=$SSH_DIR/known_hosts -o IdentitiesOnly=yes -o BatchMode=yes"
target="$DEPLOY_USER@$DEPLOY_HOST:$DEPLOY_PATH"
# The app's own folders, each mirrored exactly (--delete within the folder only). public/ is
# not in the repo (gitignored) and not deployed - the server's own copy stays.
# src/ is needed at runtime: swagger-jsdoc reads the route docs from src/models/**/*.ts.
for dir in dist src node_modules; do
rsync -az --delete -e "$rsh" "$dir/" "$target/$dir/"
done
# Single files at the top level, without --delete: .env, logs/ and tmp/ live there too.
# package.json is what makes Node treat dist/ as ES modules ("type": "module").
rsync -az -e "$rsh" package.json package-lock.json "$target/"
- name: Restart
if: github.event_name == 'push' && github.ref == 'refs/heads/master'
run: |
# Passenger restarts the app on its next request when tmp/restart.txt is touched.
ssh -p "${DEPLOY_PORT:-22}" -i "$SSH_DIR/key" -o "UserKnownHostsFile=$SSH_DIR/known_hosts" \
-o IdentitiesOnly=yes -o BatchMode=yes "$DEPLOY_USER@$DEPLOY_HOST" \
"mkdir -p '$DEPLOY_PATH/tmp' && touch '$DEPLOY_PATH/tmp/restart.txt'"
# Set DEPLOY_SMOKE_URL to a page that must answer 200 without a key, e.g.
# https://api.plutodev.de/docs/ (the Swagger UI; also proves src/ was deployed).
- name: Smoke test
if: github.event_name == 'push' && github.ref == 'refs/heads/master' && vars.DEPLOY_SMOKE_URL != ''
env:
DEPLOY_SMOKE_URL: ${{ vars.DEPLOY_SMOKE_URL }}
run: |
# Passenger starts the app on the first request after the restart; give it a moment.
for _ in 1 2 3 4 5 6; do
if curl -fsS -o /dev/null "$DEPLOY_SMOKE_URL"; then echo "OK: $DEPLOY_SMOKE_URL"; exit 0; fi
sleep 5
done
echo "Smoke test failed: $DEPLOY_SMOKE_URL"
exit 1
- name: Remove key
if: always() && github.event_name == 'push' && github.ref == 'refs/heads/master'
run: rm -f "$SSH_DIR/key"
+1
View File
@@ -8,3 +8,4 @@ dist/
logs/ logs/
node_modules/ node_modules/
public/ public/
coverage/
+1
View File
@@ -0,0 +1 @@
26
+108
View File
@@ -0,0 +1,108 @@
# Deployment
`api.plutodev.de` runs on the Plesk server as a Node.js app (Phusion Passenger) and is deployed by
**Gitea Actions** (`.gitea/workflows/deploy.yml`), which replaces the Jenkins job (switchover
2026-11). Same workflow as `Paddy/api.pmueller.me` and the Nachklang API; the reusable how-to is in
Patrick's PKM ("Jenkins to Gitea Actions for a Plesk Node.js App").
```
push to master ──▶ Gitea ──▶ runner (container on the server)
└─ one job: npm ci, tsc --noEmit, npm test (Node 26)
└─ (master only) build, prune dev deps ─ rsync over SSH ─▶
plesk-plutodev@pmueller.me:/var/www/vhosts/plutodev.de/api.plutodev.de
+ tmp/restart.txt
```
## Plesk (as configured, 2026-11-16)
*Websites & Domains → api.plutodev.de → Node.js*:
| Setting | Value |
|---|---|
| Node.js version | **26** - switched from 12.22.12 (end of life since 2022) with the Gitea switchover, see "Node version" |
| Application root | `/api.plutodev.de` (= `/var/www/vhosts/plutodev.de/api.plutodev.de`) |
| Document root | `/api.plutodev.de/public` |
| Application startup file | `dist/app.js` |
| Application mode | production |
| Environment variable | `PORT=443` (Passenger takes over the port) |
## Configuration: `.env` lives on the server
The app reads its settings from `.env` in the app root (`dotenv`): database credentials and names,
`TWITCH_HIGHLIGHTS_ACCESS_KEY`, `HCAPTCHA_SECRET`, ... The Jenkins job **wrote that file on every
deploy** from its own credentials. The workflow never touches it: since the switchover the `.env` on
the server is the source of truth and is edited there (Plesk file manager), or the values move to
Plesk's *Node.js → Environment → Secrets*. Nothing secret is stored in Gitea for this app.
The code also reads `CRAWLER_ACCESS_KEY`, which the Jenkins-generated `.env` never contained
(2026-11-16) - either unused or set elsewhere; not checked.
## What the deploy touches - and what it must not
| Path | How | Why it's needed at runtime |
|---|---|---|
| `dist/` | mirrored (`--delete` inside) | the compiled app |
| `src/` | mirrored | swagger-jsdoc reads `./src/models/**/*.router.ts` for `/docs` |
| `node_modules/` | mirrored, production dependencies only (`npm prune --omit=dev`) | runtime dependencies |
| `package.json`, `package-lock.json` | copied, no delete | (CommonJS - the app ran without them) |
**Never touched**: `.env`, `logs/` (Winston), `tmp/` (Passenger's `restart.txt`), `public/` (Passenger's
document root; gitignored in this repo, and Jenkins never copied it either).
## Node version
Until 2026-11-16 Plesk ran this app on **Node 12.22.12**; with the switchover it moves to **26**
(`.nvmrc` 26, so CI builds and tests with the same version).
Checked locally (2026-11-16), as **x86_64** like the runner (`podman --platform linux/amd64`):
`npm ci` on Node 26 downloads bcrypt 5.0.1's prebuilt N-API binary (`napi-v3`), `tsc`, the test,
build and prune pass, and the pruned bundle starts under Node 26 *and* under Node 12.22.12 (`/docs/`
200, `bcrypt` loads). So the order doesn't matter: the first deploy may land while Plesk still says
12, then switch Plesk to 26. Database queries were not exercised (no DB) - check one endpoint per
app after the switch.
Don't test this on the Mac's default (arm64) containers: bcrypt 5.0.1 has no arm64 prebuilt, so npm
compiles it there, and that compile fails on Node 26 - a local artefact, not what the runner does.
## Gitea settings
The repo belongs to the **organisation `PlutoDev`**, so user-level settings of `Paddy` don't apply.
On the organisation (*PlutoDev → Settings → Actions*), for all PlutoDev repos: secrets
`DEPLOY_SSH_KEY` (the shared private deploy key `gitea-actions Paddy` - PlutoDev is a private project
now), `DEPLOY_KNOWN_HOSTS` (`[pmueller.me]:42069 ssh-ed25519 …`, same server); variables
`DEPLOY_HOST=pmueller.me`, `DEPLOY_PORT=42069`, `DEPLOY_USER=plesk-plutodev`.
On this repository (*plutoapi-v2 → Settings → Actions → Variables*):
| Variable | Value |
|---|---|
| `DEPLOY_PATH` | `/var/www/vhosts/plutodev.de/api.plutodev.de` |
| `DEPLOY_SMOKE_URL` | `https://api.plutodev.de/docs/` |
## Switchover
1. SSH for `plesk-plutodev` (was `/bin/false`, set to `/bin/bash` 2026-11-16, done): the shared public key
appended to `/var/www/vhosts/plutodev.de/.ssh/authorized_keys` (`.ssh` `700`, file `600`), the user
added to the key-only `Match User …` line in `/etc/ssh/sshd_config`.
2. Pause the Jenkins job (done 2026-11-16). Its credentials (`DB_USER`, `DB_PASSWORD`, `TWITCH_HIGHLIGHTS_ACCESS_KEY`,
`HCAPTCHA_SECRET`) can be deleted from Jenkins afterwards - they're in the server's `.env`.
3. **Fix file ownership** (as root): `ls -ld .` first (the folder keeps its group), then
`find . -mindepth 1 ! -user plesk-plutodev -exec chown -h plesk-plutodev:psacln {} +` - `-h` for
the symlinks in `node_modules/.bin/`.
4. Set the variables, open a PR → green run → merge → watch the deploy, check `/docs/`.
5. Plesk → *api.plutodev.de → Node.js*: version 26, restart; check `/docs/` and one endpoint per app.
Rollback: revert the commit on `master`; the workflow deploys the previous state.
## Cleaned up with the switchover (2026-11-16)
- SonarQube is gone: `sonar-project.properties`, `jest-sonar-reporter`, the `--coverage
--testResultsProcessor` flags and the `jestSonar` config.
## Checked locally (2026-11-16)
- `actionlint`: no findings.
- `node:26-bookworm` (x86_64): `npm ci`, `tsc --noEmit`, `npm test`, build, `npm prune --omit=dev`;
the bundle then ran under Node 26 and Node 12 (see "Node version").
Not checked: the workflow on the real runner.
+19 -2
View File
@@ -30,8 +30,25 @@ 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 // Swagger documentation
const swaggerDefinition = { const swaggerDefinition = {
+8
View File
@@ -0,0 +1,8 @@
/** @type {import('ts-jest/dist/types').InitialOptionsTsJest} */
module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
roots: [
'test'
]
};
+9101 -800
View File
File diff suppressed because it is too large. Load diff
+10 -6
View File
@@ -7,8 +7,7 @@
"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"
"swagger": "tsoa spec"
}, },
"keywords": [], "keywords": [],
"author": "", "author": "",
@@ -20,9 +19,9 @@
"cors": "^2.8.5", "cors": "^2.8.5",
"debug": "^4.3.1", "debug": "^4.3.1",
"dotenv": "^8.2.0", "dotenv": "^8.2.0",
"express": "^4.17.1", "express": "^4.18.2",
"guid-typescript": "^1.0.9", "guid-typescript": "^1.0.9",
"mariadb": "^2.5.3", "mariadb": "^3.0.2",
"random-words": "^1.1.1", "random-words": "^1.1.1",
"swagger-jsdoc": "^6.1.0", "swagger-jsdoc": "^6.1.0",
"swagger-ui-express": "^4.3.0", "swagger-ui-express": "^4.3.0",
@@ -32,13 +31,18 @@
"@types/app-root-path": "^1.2.4", "@types/app-root-path": "^1.2.4",
"@types/bcrypt": "^3.0.1", "@types/bcrypt": "^3.0.1",
"@types/debug": "^4.1.5", "@types/debug": "^4.1.5",
"@types/express": "^4.17.11", "@types/express": "^4.17.15",
"@types/jest": "^28.1.3",
"@types/node": "^18.11.17",
"@types/random-words": "^1.1.2", "@types/random-words": "^1.1.2",
"@types/swagger-jsdoc": "^6.0.1", "@types/swagger-jsdoc": "^6.0.1",
"@types/swagger-ui-express": "^4.1.3", "@types/swagger-ui-express": "^4.1.3",
"@types/winston": "^2.4.4", "@types/winston": "^2.4.4",
"is-number": "^7.0.0",
"jest": "^28.1.1",
"source-map-support": "^0.5.19", "source-map-support": "^0.5.19",
"ts-jest": "^28.0.5",
"tslint": "^6.1.3", "tslint": "^6.1.3",
"typescript": "^4.1.5" "typescript": "^4.9.4"
} }
} }
+3 -3
View File
@@ -13,7 +13,7 @@ export namespace BetterzonDB {
connectionLimit: 5 connectionLimit: 5
}); });
export function getConnection() { export const getConnection = async () => {
return pool; return pool.getConnection();
} };
} }
+1 -1
View File
@@ -35,7 +35,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 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({
@@ -25,7 +25,7 @@ categoriesRouter.get('/', async (req: Request, res: Response) => {
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.'}));
} }
@@ -44,7 +44,7 @@ categoriesRouter.get('/:id', async (req: Request, res: Response) => {
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.'}));
} }
@@ -63,7 +63,7 @@ categoriesRouter.get('/search/:term', async (req: Request, res: Response) => {
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.'}));
} }
@@ -18,7 +18,7 @@ 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 = await BetterzonDB.getConnection();
let categRows = []; let categRows = [];
try { try {
const rows = await conn.query('SELECT category_id, name FROM categories'); const rows = await conn.query('SELECT category_id, name FROM categories');
@@ -38,6 +38,9 @@ export const findAll = async (): Promise<Categories> => {
} catch (err) { } catch (err) {
throw err; throw err;
} finally {
// Return connection
await conn.end();
} }
return categRows; return categRows;
@@ -48,7 +51,7 @@ 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 = await BetterzonDB.getConnection();
let categ: any; let categ: any;
try { try {
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);
@@ -60,6 +63,9 @@ export const find = async (id: number): Promise<Category> => {
} catch (err) { } catch (err) {
throw err; throw err;
} finally {
// Return connection
await conn.end();
} }
return categ; return categ;
@@ -70,7 +76,7 @@ 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 = await BetterzonDB.getConnection();
let categRows = []; let categRows = [];
try { try {
term = '%' + term + '%'; term = '%' + term + '%';
@@ -83,6 +89,9 @@ export const findBySearchTerm = async (term: string): Promise<Categories> => {
} catch (err) { } catch (err) {
throw err; throw err;
} finally {
// Return connection
await conn.end();
} }
return categRows; return categRows;
@@ -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';
/** /**
@@ -27,7 +26,7 @@ contactpersonsRouter.get('/', async (req: Request, res: Response) => {
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.'}));
} }
@@ -46,7 +45,7 @@ contactpersonsRouter.get('/:id', async (req: Request, res: Response) => {
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.'}));
} }
@@ -65,7 +64,7 @@ contactpersonsRouter.get('/byvendor/:id', async (req: Request, res: Response) =>
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.'}));
} }
@@ -95,7 +94,7 @@ contactpersonsRouter.post('/', async (req: Request, res: Response) => {
} 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.'}));
} }
@@ -126,7 +125,7 @@ contactpersonsRouter.put('/:id', async (req: Request, res: Response) => {
} 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.'}));
} }
@@ -18,7 +18,7 @@ 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 = await BetterzonDB.getConnection();
let contRows = []; let contRows = [];
try { try {
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');
@@ -30,6 +30,9 @@ export const findAll = async (): Promise<Contact_Persons> => {
} catch (err) { } catch (err) {
throw err; throw err;
} finally {
// Return connection
await conn.end();
} }
return contRows; return contRows;
@@ -40,7 +43,7 @@ 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 = await BetterzonDB.getConnection();
let cont: any; let cont: any;
try { try {
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);
@@ -52,6 +55,9 @@ export const find = async (id: number): Promise<Contact_Person> => {
} catch (err) { } catch (err) {
throw err; throw err;
} finally {
// Return connection
await conn.end();
} }
return cont; return cont;
@@ -62,7 +68,7 @@ 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 = await BetterzonDB.getConnection();
let contRows = []; let contRows = [];
try { try {
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);
@@ -74,6 +80,9 @@ export const findByVendor = async (id: number): Promise<Contact_Persons> => {
} catch (err) { } catch (err) {
throw err; throw err;
} finally {
// Return connection
await conn.end();
} }
return contRows; return contRows;
@@ -90,7 +99,7 @@ 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 = await BetterzonDB.getConnection();
try { try {
// 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]);
@@ -105,6 +114,9 @@ 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 {
// Return connection
await conn.end();
} }
}; };
@@ -120,7 +132,7 @@ 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 = await BetterzonDB.getConnection();
try { try {
// 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]);
@@ -135,5 +147,8 @@ 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 {
// Return connection
await conn.end();
} }
}; };
@@ -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';
@@ -37,7 +36,7 @@ crawlingstatusRouter.get('/', async (req: Request, res: Response) => {
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.'}));
} }
@@ -17,7 +17,7 @@ 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 = await BetterzonDB.getConnection();
try { try {
// Get the current crawling process // Get the current crawling process
let process_info = { let process_info = {
@@ -55,5 +55,8 @@ export const getCurrent = async (): Promise<Crawling_Status> => {
} catch (err) { } catch (err) {
throw err; throw err;
} finally {
// Return connection
await conn.end();
} }
}; };
@@ -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';
@@ -31,7 +29,7 @@ favoriteshopsRouter.get('/', async (req: Request, res: Response) => {
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.'}));
} }
@@ -65,7 +63,7 @@ favoriteshopsRouter.post('/', async (req: Request, res: Response) => {
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.'}));
} }
@@ -99,7 +97,7 @@ favoriteshopsRouter.delete('/:id', async (req: Request, res: Response) => {
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.'}));
} }
@@ -19,13 +19,16 @@ 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 = await BetterzonDB.getConnection();
try { try {
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 {
// Return connection
await conn.end();
} }
}; };
@@ -34,7 +37,7 @@ 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 = await BetterzonDB.getConnection();
let shops = []; let shops = [];
try { try {
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);
@@ -47,6 +50,9 @@ export const getFavoriteShops = async (user_id: number): Promise<FavoriteShops>
return shops; return shops;
} catch (err) { } catch (err) {
throw err; throw err;
} finally {
// Return connection
await conn.end();
} }
}; };
@@ -56,12 +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 = BetterzonDB.getConnection(); let conn = await BetterzonDB.getConnection();
try { try {
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 {
// Return connection
await conn.end();
} }
}; };
@@ -25,7 +25,7 @@ manufacturersRouter.get('/', async (req: Request, res: Response) => {
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.'}));
} }
@@ -44,7 +44,7 @@ manufacturersRouter.get('/:id', async (req: Request, res: Response) => {
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.'}));
} }
@@ -63,7 +63,7 @@ manufacturersRouter.get('/search/:term', async (req: Request, res: Response) =>
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.'}));
} }
@@ -18,7 +18,7 @@ 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 = await BetterzonDB.getConnection();
let manRows = []; let manRows = [];
try { try {
const rows = await conn.query('SELECT manufacturer_id, name FROM manufacturers'); const rows = await conn.query('SELECT manufacturer_id, name FROM manufacturers');
@@ -38,6 +38,9 @@ export const findAll = async (): Promise<Manufacturers> => {
} catch (err) { } catch (err) {
throw err; throw err;
} finally {
// Return connection
await conn.end();
} }
return manRows; return manRows;
@@ -48,7 +51,7 @@ 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 = await BetterzonDB.getConnection();
let man: any; let man: any;
try { try {
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);
@@ -60,6 +63,9 @@ export const find = async (id: number): Promise<Manufacturer> => {
} catch (err) { } catch (err) {
throw err; throw err;
} finally {
// Return connection
await conn.end();
} }
return man; return man;
@@ -70,7 +76,7 @@ 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 = await BetterzonDB.getConnection();
let manRows = []; let manRows = [];
try { try {
term = '%' + term + '%'; term = '%' + term + '%';
@@ -83,6 +89,9 @@ export const findBySearchTerm = async (term: string): Promise<Manufacturers> =>
} catch (err) { } catch (err) {
throw err; throw err;
} finally {
// Return connection
await conn.end();
} }
return manRows; return manRows;
@@ -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';
@@ -31,7 +29,7 @@ pricealarmsRouter.get('/', async (req: Request, res: Response) => {
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.'}));
} }
@@ -66,7 +64,7 @@ pricealarmsRouter.post('/', async (req: Request, res: Response) => {
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.'}));
} }
@@ -101,7 +99,7 @@ pricealarmsRouter.put('/', async (req: Request, res: Response) => {
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.'}));
} }
@@ -127,7 +125,7 @@ pricealarmsRouter.delete('/:id', async (req, res) => {
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.'}));
} }
@@ -20,13 +20,16 @@ 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 = await BetterzonDB.getConnection();
try { try {
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 {
// Return connection
await conn.end();
} }
}; };
@@ -35,7 +38,7 @@ 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 = await BetterzonDB.getConnection();
let priceAlarms = []; let priceAlarms = [];
try { try {
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);
@@ -48,6 +51,9 @@ export const getPriceAlarms = async (user_id: number): Promise<PriceAlarms> => {
return priceAlarms; return priceAlarms;
} catch (err) { } catch (err) {
throw err; throw err;
} finally {
// Return connection
await conn.end();
} }
}; };
@@ -58,13 +64,16 @@ 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 = await BetterzonDB.getConnection();
try { try {
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 {
// Return connection
await conn.end();
} }
}; };
@@ -74,12 +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 = BetterzonDB.getConnection(); let conn = await BetterzonDB.getConnection();
try { try {
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 {
// Return connection
await conn.end();
} }
}; };
+5 -5
View File
@@ -39,7 +39,7 @@ pricesRouter.get('/', async (req: Request, res: Response) => {
} }
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.'}));
} }
@@ -58,7 +58,7 @@ pricesRouter.get('/:id', async (req: Request, res: Response) => {
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.'}));
} }
@@ -77,7 +77,7 @@ pricesRouter.get('/bestDeals/:amount', async (req: Request, res: Response) => {
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.'}));
} }
@@ -96,7 +96,7 @@ pricesRouter.get('/byProduct/list/:ids', async (req: Request, res: Response) =>
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.'}));
} }
@@ -123,7 +123,7 @@ pricesRouter.post('/', async (req: Request, res: Response) => {
} 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.'}));
} }
+32 -8
View File
@@ -18,7 +18,7 @@ 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 = await BetterzonDB.getConnection();
let priceRows = []; let priceRows = [];
try { try {
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');
@@ -44,6 +44,9 @@ export const findAll = async (): Promise<Prices> => {
} catch (err) { } catch (err) {
throw err; throw err;
} finally {
// Return connection
await conn.end();
} }
return priceRows; return priceRows;
@@ -54,7 +57,7 @@ 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 = await BetterzonDB.getConnection();
let price: any; let price: any;
try { try {
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);
@@ -66,6 +69,9 @@ export const find = async (id: number): Promise<Price> => {
} catch (err) { } catch (err) {
throw err; throw err;
} finally {
// Return connection
await conn.end();
} }
return price; return price;
@@ -76,7 +82,7 @@ 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 = await BetterzonDB.getConnection();
let priceRows = []; let priceRows = [];
try { try {
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);
@@ -88,6 +94,9 @@ export const findByProduct = async (product: number): Promise<Prices> => {
} catch (err) { } catch (err) {
throw err; throw err;
} finally {
// Return connection
await conn.end();
} }
return priceRows; return priceRows;
@@ -102,7 +111,7 @@ 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 = await BetterzonDB.getConnection();
let priceRows = []; let priceRows = [];
try { try {
let rows = []; let rows = [];
@@ -138,6 +147,9 @@ export const findByType = async (product: string, type: string): Promise<Prices>
} catch (err) { } catch (err) {
throw err; throw err;
} finally {
// Return connection
await conn.end();
} }
return priceRows; return priceRows;
@@ -153,7 +165,7 @@ 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 = await BetterzonDB.getConnection();
let priceRows = []; let priceRows = [];
try { try {
let rows = []; let rows = [];
@@ -176,6 +188,9 @@ export const findByVendor = async (product: string, vendor: string, type: string
} catch (err) { } catch (err) {
throw err; throw err;
} finally {
// Return connection
await conn.end();
} }
return priceRows; return priceRows;
@@ -187,7 +202,7 @@ 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 = await BetterzonDB.getConnection();
let priceRows = []; let priceRows = [];
try { try {
let allPrices: Record<number, Price[]> = {}; let allPrices: Record<number, Price[]> = {};
@@ -268,6 +283,9 @@ export const getBestDeals = async (amount: number): Promise<Prices> => {
} catch (err) { } catch (err) {
console.log(err); console.log(err);
throw err; throw err;
} finally {
// Return connection
await conn.end();
} }
return priceRows; return priceRows;
@@ -278,7 +296,7 @@ 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 = await BetterzonDB.getConnection();
let priceRows: Price[] = []; let priceRows: Price[] = [];
try { try {
let allPrices: Record<number, Price[]> = {}; let allPrices: Record<number, Price[]> = {};
@@ -325,13 +343,16 @@ export const findListByProducts = async (productIds: [number]): Promise<Prices>
}); });
} catch (err) { } catch (err) {
throw err; throw err;
} finally {
// Return connection
await 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 = await BetterzonDB.getConnection();
try { try {
// 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]);
@@ -346,5 +367,8 @@ 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 {
// Return connection
await conn.end();
} }
}; };
@@ -25,7 +25,7 @@ productsRouter.get('/', async (req: Request, res: Response) => {
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.'}));
} }
@@ -44,7 +44,7 @@ productsRouter.get('/:id', async (req: Request, res: Response) => {
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.'}));
} }
@@ -63,7 +63,7 @@ productsRouter.get('/search/:term', async (req: Request, res: Response) => {
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.'}));
} }
@@ -82,7 +82,7 @@ productsRouter.get('/list/:ids', async (req: Request, res: Response) => {
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.'}));
} }
@@ -101,7 +101,7 @@ productsRouter.get('/vendor/:id', async (req: Request, res: Response) => {
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.'}));
} }
@@ -124,7 +124,7 @@ productsRouter.post('/', async (req: Request, res: Response) => {
} 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.'}));
} }
@@ -19,7 +19,7 @@ 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 = await BetterzonDB.getConnection();
let prodRows = []; let prodRows = [];
try { try {
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');
@@ -59,6 +59,9 @@ export const findAll = async (): Promise<Products> => {
} catch (err) { } catch (err) {
throw err; throw err;
} finally {
// Return connection
await conn.end();
} }
return prodRows; return prodRows;
@@ -69,7 +72,7 @@ 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 = await BetterzonDB.getConnection();
let prod: any; let prod: any;
try { try {
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);
@@ -81,6 +84,9 @@ export const find = async (id: number): Promise<Product> => {
} catch (err) { } catch (err) {
throw err; throw err;
} finally {
// Return connection
await conn.end();
} }
return prod; return prod;
@@ -91,7 +97,7 @@ 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 = await BetterzonDB.getConnection();
let prodRows = []; let prodRows = [];
try { try {
term = '%' + term + '%'; term = '%' + term + '%';
@@ -105,6 +111,9 @@ export const findBySearchTerm = async (term: string): Promise<Products> => {
} catch (err) { } catch (err) {
console.log(err); console.log(err);
throw err; throw err;
} finally {
// Return connection
await conn.end();
} }
return prodRows; return prodRows;
@@ -115,7 +124,7 @@ 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 = await BetterzonDB.getConnection();
let prodRows = []; let prodRows = [];
try { try {
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]);
@@ -127,6 +136,9 @@ export const findList = async (ids: [number]): Promise<Products> => {
} catch (err) { } catch (err) {
throw err; throw err;
} finally {
// Return connection
await conn.end();
} }
return prodRows; return prodRows;
@@ -137,7 +149,7 @@ 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 = await BetterzonDB.getConnection();
let prodRows = []; let prodRows = [];
try { try {
// Get the relevant product ids // Get the relevant product ids
@@ -159,6 +171,9 @@ export const findByVendor = async (id: number): Promise<Products> => {
} catch (err) { } catch (err) {
throw err; throw err;
} finally {
// Return connection
await conn.end();
} }
return prodRows; return prodRows;
+3 -4
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';
@@ -51,7 +50,7 @@ usersRouter.post('/register', async (req: Request, res: Response) => {
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.'}));
} }
@@ -84,7 +83,7 @@ usersRouter.post('/login', async (req: Request, res: Response) => {
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.'}));
} }
@@ -114,7 +113,7 @@ usersRouter.post('/checkSessionValid', async (req: Request, res: Response) => {
// 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.'}));
} }
+16 -8
View File
@@ -21,7 +21,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 = 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);
@@ -63,9 +63,10 @@ export const createUser = async (username: string, password: string, email: stri
} catch (err) { } catch (err) {
throw err; throw err;
} finally {
// Return connection
await conn.end();
} }
return {} as Session;
}; };
/** /**
@@ -73,7 +74,7 @@ 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 = await BetterzonDB.getConnection();
try { try {
// Get saved password hash // Get saved password hash
const query = 'SELECT user_id, bcrypt_password_hash FROM users WHERE username = ?'; const query = 'SELECT user_id, bcrypt_password_hash FROM users WHERE username = ?';
@@ -125,16 +126,17 @@ export const login = async (username: string, password: string, ip: string): Pro
} catch (err) { } catch (err) {
throw err; throw err;
} finally {
// Return connection
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 = BetterzonDB.getConnection(); let conn = await BetterzonDB.getConnection();
try { try {
// Get saved session key hash // Get saved session key hash
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 = ?';
@@ -202,6 +204,9 @@ export const checkSession = async (sessionId: string, sessionKey: string, ip: st
} catch (err) { } catch (err) {
throw err; throw err;
} finally {
// Return connection
await conn.end();
} }
}; };
@@ -234,7 +239,7 @@ 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 = await BetterzonDB.getConnection();
try { try {
// Create user entry in SQL // Create user entry in SQL
const usernameQuery = 'SELECT username FROM users WHERE username = ?'; const usernameQuery = 'SELECT username FROM users WHERE username = ?';
@@ -282,5 +287,8 @@ export const checkUsernameAndEmail = async (username: string, email: string): Pr
} catch (err) { } catch (err) {
throw err; throw err;
} finally {
// Return connection
await conn.end();
} }
}; };
+7 -7
View File
@@ -26,7 +26,7 @@ vendorsRouter.get('/', async (req: Request, res: Response) => {
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.'}));
} }
@@ -44,7 +44,7 @@ vendorsRouter.get('/managed', async (req: Request, res: Response) => {
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.'}));
} }
@@ -63,7 +63,7 @@ vendorsRouter.get('/:id', async (req: Request, res: Response) => {
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.'}));
} }
@@ -82,7 +82,7 @@ vendorsRouter.get('/search/:term', async (req: Request, res: Response) => {
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.'}));
} }
@@ -108,7 +108,7 @@ vendorsRouter.put('/manage/deactivatelisting', async (req: Request, res: Respons
} 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.'}));
} }
@@ -133,7 +133,7 @@ vendorsRouter.put('/manage/shop/deactivate/:id', async (req: Request, res: Respo
} 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.'}));
} }
@@ -158,7 +158,7 @@ vendorsRouter.put('/manage/shop/activate/:id', async (req: Request, res: Respons
} 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.'}));
} }
+24 -10
View File
@@ -18,7 +18,7 @@ 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 = await BetterzonDB.getConnection();
let vendorRows = []; let vendorRows = [];
try { try {
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');
@@ -50,6 +50,9 @@ export const findAll = async (): Promise<Vendors> => {
} catch (err) { } catch (err) {
throw err; throw err;
} finally {
// Return connection
await conn.end();
} }
return vendorRows; return vendorRows;
@@ -60,7 +63,7 @@ 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 = await BetterzonDB.getConnection();
let vendor: any; let vendor: any;
try { try {
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);
@@ -72,6 +75,9 @@ export const find = async (id: number): Promise<Vendor> => {
} catch (err) { } catch (err) {
throw err; throw err;
} finally {
// Return connection
await conn.end();
} }
return vendor; return vendor;
@@ -82,7 +88,7 @@ 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 = await BetterzonDB.getConnection();
let vendorRows = []; let vendorRows = [];
try { try {
term = '%' + term + '%'; term = '%' + term + '%';
@@ -95,6 +101,9 @@ export const findBySearchTerm = async (term: string): Promise<Vendors> => {
} catch (err) { } catch (err) {
throw err; throw err;
} finally {
// Return connection
await conn.end();
} }
return vendorRows; return vendorRows;
@@ -105,7 +114,7 @@ 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 = await BetterzonDB.getConnection();
let vendorRows = []; let vendorRows = [];
try { try {
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);
@@ -117,6 +126,9 @@ export const getManagedShops = async (user_id: number): Promise<Vendors> => {
} catch (err) { } catch (err) {
throw err; throw err;
} finally {
// Return connection
await conn.end();
} }
return vendorRows; return vendorRows;
@@ -129,7 +141,7 @@ 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 = await BetterzonDB.getConnection();
try { try {
// 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]);
@@ -142,9 +154,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 {
// Return connection
await conn.end();
} }
return false;
}; };
/** /**
@@ -154,7 +167,7 @@ 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 = await BetterzonDB.getConnection();
try { try {
// 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]);
@@ -168,7 +181,8 @@ 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 {
// Return connection
await conn.end();
} }
return false;
}; };
@@ -13,7 +13,7 @@ export namespace ClimbingRouteRatingDB {
connectionLimit: 5 connectionLimit: 5
}); });
export function getConnection() { export const getConnection = async () => {
return pool; return pool.getConnection();
} };
} }
@@ -23,7 +23,7 @@ crrRouter.use('/ratings', routeRatingsRouter);
crrRouter.get('/', async (req: Request, res: Response) => { crrRouter.get('/', async (req: Request, res: Response) => {
try { try {
res.status(200).send('Pluto Development Climbing Route Rating API Endpoint'); res.status(200).send('Pluto Development Climbing Route Rating 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({
@@ -13,12 +13,49 @@ import {verifyCaptcha} from '../common/VerifyCaptcha';
*/ */
export const climbingGymRouter = express.Router(); 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) => { climbingGymRouter.get('/', async (req: Request, res: Response) => {
try { try {
const gyms: ClimbingGym[] = await GymService.findAll(); const gyms: ClimbingGym[] = await GymService.findAll();
res.status(200).send(gyms); res.status(200).send(gyms);
} 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({
@@ -29,11 +66,60 @@ climbingGymRouter.get('/', async (req: Request, res: Response) => {
} }
}); });
/**
* @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) => { climbingGymRouter.post('/', async (req: Request, res: Response) => {
try { try {
let name = req.query.name as string; let name = req.query.name as string;
let city = req.query.city as string; let city = req.query.city as string;
let captcha_token = req.query['h-captcha-response'] as string; let captcha_token = req.query['hcaptcha_response'] as string;
if (!name || !city || !captcha_token) { if (!name || !city || !captcha_token) {
res.status(400).send({'message': 'Missing parameters'}); res.status(400).send({'message': 'Missing parameters'});
@@ -41,7 +127,8 @@ climbingGymRouter.post('/', async (req: Request, res: Response) => {
} }
// Verify captcha // Verify captcha
if (!await verifyCaptcha(captcha_token)) { let success = await verifyCaptcha(captcha_token);
if (!success) {
res.status(403).send({'message': 'Invalid Captcha. Please try again.'}); res.status(403).send({'message': 'Invalid Captcha. Please try again.'});
return; return;
} }
@@ -53,7 +140,7 @@ climbingGymRouter.post('/', async (req: Request, res: Response) => {
} else { } else {
res.status(500).send({}); res.status(500).send({});
} }
} 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({
@@ -6,11 +6,14 @@ import {ClimbingGym} from './ClimbingGym.interface';
* @return Promise<ClimbingHall[]> The climbing halls * @return Promise<ClimbingHall[]> The climbing halls
*/ */
export const findAll = async (): Promise<ClimbingGym[]> => { export const findAll = async (): Promise<ClimbingGym[]> => {
let conn = ClimbingRouteRatingDB.getConnection(); let conn = await ClimbingRouteRatingDB.getConnection();
try { try {
return await conn.query('SELECT gym_id, name, city, verified FROM climbing_gyms'); return await conn.query('SELECT gym_id, name, city, verified FROM climbing_gyms');
} catch (err) { } catch (err) {
throw err; throw err;
} finally {
// Return connection
await conn.end();
} }
}; };
@@ -21,13 +24,16 @@ export const findAll = async (): Promise<ClimbingGym[]> => {
* @return number The id of the climbing hall * @return number The id of the climbing hall
*/ */
export const createGym = async (name: string, city: string): Promise<number> => { export const createGym = async (name: string, city: string): Promise<number> => {
let conn = ClimbingRouteRatingDB.getConnection(); let conn = await ClimbingRouteRatingDB.getConnection();
try { try {
let res = await conn.query('INSERT INTO climbing_gyms (name, city) VALUES (?, ?) RETURNING gym_id', [name, city]); let res = await conn.query('INSERT INTO climbing_gyms (name, city) VALUES (?, ?) RETURNING gym_id', [name, city]);
return res[0].hall_id; return res[0].gym_id;
} catch (err) { } catch (err) {
throw err; throw err;
} finally {
// Return connection
await conn.end();
} }
}; };
@@ -13,12 +13,53 @@ import {verifyCaptcha} from '../common/VerifyCaptcha';
*/ */
export const climbingRoutesRouter = express.Router(); 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) => { climbingRoutesRouter.get('/', async (req: Request, res: Response) => {
try { try {
const routes: ClimbingRoute[] = await RouteService.findAll(); const routes: ClimbingRoute[] = await RouteService.findAll();
res.status(200).send(routes); res.status(200).send(routes);
} 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({
@@ -29,6 +70,55 @@ climbingRoutesRouter.get('/', async (req: Request, res: Response) => {
} }
}); });
/**
* @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) => { climbingRoutesRouter.get('/:id', async (req: Request, res: Response) => {
try { try {
let route_id = req.params.id; let route_id = req.params.id;
@@ -36,7 +126,7 @@ climbingRoutesRouter.get('/:id', async (req: Request, res: Response) => {
const route: ClimbingRoute = await RouteService.findById(route_id); const route: ClimbingRoute = await RouteService.findById(route_id);
res.status(200).send(route); res.status(200).send(route);
} 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({
@@ -47,12 +137,68 @@ climbingRoutesRouter.get('/:id', async (req: Request, res: Response) => {
} }
}); });
/**
* @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) => { climbingRoutesRouter.post('/', async (req: Request, res: Response) => {
try { try {
let gym_id = Number(req.query.gym_id); let gym_id = Number(req.query.gym_id);
let name = req.query.name as string; let name = req.query.name as string;
let difficulty = req.query.difficulty as string; let difficulty = req.query.difficulty as string;
let captcha_token = req.query['h-captcha-response'] as string; let captcha_token = req.query['hcaptcha_response'] as string;
if (isNaN(gym_id) || !name || !difficulty || !captcha_token) { if (isNaN(gym_id) || !name || !difficulty || !captcha_token) {
res.status(400).send({'message': 'Missing parameters'}); res.status(400).send({'message': 'Missing parameters'});
@@ -68,7 +214,7 @@ climbingRoutesRouter.post('/', async (req: Request, res: Response) => {
let route_id = await RouteService.createRoute(gym_id, name, difficulty); let route_id = await RouteService.createRoute(gym_id, name, difficulty);
res.status(201).send({'route_id': route_id}); res.status(201).send({'route_id': route_id});
} 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({
@@ -7,11 +7,14 @@ import random from 'random-words';
* @return Promise<ClimbingRoute[]> The climbing routes * @return Promise<ClimbingRoute[]> The climbing routes
*/ */
export const findAll = async (): Promise<ClimbingRoute[]> => { export const findAll = async (): Promise<ClimbingRoute[]> => {
let conn = ClimbingRouteRatingDB.getConnection(); let conn = await ClimbingRouteRatingDB.getConnection();
try { try {
return await conn.query('SELECT route_id, gym_id, name, difficulty, route_setting_date FROM climbing_routes'); return await conn.query('SELECT route_id, gym_id, name, difficulty, route_setting_date FROM climbing_routes');
} catch (err) { } catch (err) {
throw err; throw err;
} finally {
// Return connection
await conn.end();
} }
}; };
@@ -21,11 +24,14 @@ export const findAll = async (): Promise<ClimbingRoute[]> => {
* @return Promise<ClimbingRoute> The climbing route * @return Promise<ClimbingRoute> The climbing route
*/ */
export const findById = async (route_id: string): Promise<ClimbingRoute> => { export const findById = async (route_id: string): Promise<ClimbingRoute> => {
let conn = ClimbingRouteRatingDB.getConnection(); let conn = await ClimbingRouteRatingDB.getConnection();
try { try {
return await conn.query('SELECT route_id, gym_id, name, difficulty, route_setting_date FROM climbing_routes WHERE route_id = ?', route_id); return await conn.query('SELECT route_id, gym_id, name, difficulty, route_setting_date FROM climbing_routes WHERE route_id = ?', route_id);
} catch (err) { } catch (err) {
throw err; throw err;
} finally {
// Return connection
await conn.end();
} }
}; };
@@ -37,7 +43,7 @@ export const findById = async (route_id: string): Promise<ClimbingRoute> => {
* @return string The id of the created route * @return string The id of the created route
*/ */
export const createRoute = async (gym_id: number, name: string, difficulty: string): Promise<string> => { export const createRoute = async (gym_id: number, name: string, difficulty: string): Promise<string> => {
let conn = ClimbingRouteRatingDB.getConnection(); let conn = await ClimbingRouteRatingDB.getConnection();
// Generate route id // Generate route id
let route_id = ''; let route_id = '';
@@ -55,5 +61,8 @@ export const createRoute = async (gym_id: number, name: string, difficulty: stri
return route_id; return route_id;
} catch (err) { } catch (err) {
throw err; throw err;
} finally {
// Return connection
await conn.end();
} }
}; };
@@ -1,22 +1,15 @@
import * as dotenv from 'dotenv'; import * as dotenv from 'dotenv';
import * as querystring from 'querystring'; import * as querystring from 'qs';
import axios from 'axios'; import axios from 'axios';
dotenv.config(); dotenv.config();
export const verifyCaptcha = async (captcha_token: string): Promise<boolean> => { export const verifyCaptcha = async (captcha_token: string): Promise<boolean> => {
var postData = querystring.stringify({ let postData = querystring.stringify({
response: captcha_token, response: captcha_token,
secret: process.env.HCAPTCHA_SECRET secret: process.env.HCAPTCHA_SECRET
}); });
axios.post('https://hcaptcha.com/siteverify', postData) let res = await axios.post('https://hcaptcha.com/siteverify', postData);
.then(res => {
return res.data.success; return res.data.success;
})
.catch(error => {
throw(error);
});
return false;
}; };
@@ -7,6 +7,51 @@ import {verifyCaptcha} from '../common/VerifyCaptcha';
export const routeCommentsRouter = express.Router(); 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) => { routeCommentsRouter.get('/by/route/:id', async (req: Request, res: Response) => {
try { try {
let route_id = req.params.id; let route_id = req.params.id;
@@ -14,7 +59,7 @@ routeCommentsRouter.get('/by/route/:id', async (req: Request, res: Response) =>
const comments: RouteComment[] = await CommentService.findByRoute(route_id); const comments: RouteComment[] = await CommentService.findByRoute(route_id);
res.status(200).send(comments); res.status(200).send(comments);
} 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({
@@ -25,11 +70,60 @@ routeCommentsRouter.get('/by/route/:id', async (req: Request, res: Response) =>
} }
}); });
/**
* @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) => { routeCommentsRouter.post('/', async (req: Request, res: Response) => {
try { try {
let route_id = req.query.route_id as string; let route_id = req.query.route_id as string;
let comment = req.query.comment as string; let comment = req.query.comment as string;
let captcha_token = req.query['h-captcha-response'] as string; let captcha_token = req.query['hcaptcha_response'] as string;
if (!route_id || !comment || !captcha_token) { if (!route_id || !comment || !captcha_token) {
res.status(400).send({'message': 'Missing parameters'}); res.status(400).send({'message': 'Missing parameters'});
@@ -49,7 +143,7 @@ routeCommentsRouter.post('/', async (req: Request, res: Response) => {
} else { } else {
res.status(500).send({}); res.status(500).send({});
} }
} 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({
@@ -6,11 +6,14 @@ import {RouteComment} from './RouteComment.interface';
* @return Promise<RouteComment[]> The comments * @return Promise<RouteComment[]> The comments
*/ */
export const findByRoute = async (route_id: string): Promise<RouteComment[]> => { export const findByRoute = async (route_id: string): Promise<RouteComment[]> => {
let conn = ClimbingRouteRatingDB.getConnection(); let conn = await ClimbingRouteRatingDB.getConnection();
try { try {
return await conn.query('SELECT comment_id, route_id, comment, timestamp FROM route_comments WHERE route_id = ?', route_id); return await conn.query('SELECT comment_id, route_id, comment, timestamp FROM route_comments WHERE route_id = ?', route_id);
} catch (err) { } catch (err) {
throw err; throw err;
} finally {
// Return connection
await conn.end();
} }
}; };
@@ -21,12 +24,15 @@ export const findByRoute = async (route_id: string): Promise<RouteComment[]> =>
* @return number The id of the comment * @return number The id of the comment
*/ */
export const createComment = async (route_id: string, comment: string): Promise<number> => { export const createComment = async (route_id: string, comment: string): Promise<number> => {
let conn = ClimbingRouteRatingDB.getConnection(); let conn = await ClimbingRouteRatingDB.getConnection();
try { try {
let res = await conn.query('INSERT INTO route_comments (route_id, comment) VALUES (?, ?) RETURNING comment_id', [route_id, comment]); let res = await conn.query('INSERT INTO route_comments (route_id, comment) VALUES (?, ?) RETURNING comment_id', [route_id, comment]);
return res[0].comment_id; return res[0].comment_id;
} catch (err) { } catch (err) {
throw err; throw err;
} finally {
// Return connection
await conn.end();
} }
}; };
@@ -6,6 +6,37 @@ import {verifyCaptcha} from '../common/VerifyCaptcha';
export const routeRatingsRouter = express.Router(); 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) => { routeRatingsRouter.get('/by/route/:id', async (req: Request, res: Response) => {
try { try {
let route_id = req.params.id; let route_id = req.params.id;
@@ -13,7 +44,7 @@ routeRatingsRouter.get('/by/route/:id', async (req: Request, res: Response) => {
let rating = await RatingService.getStarsForRoute(route_id); let rating = await RatingService.getStarsForRoute(route_id);
res.status(200).send({'rating': rating}); res.status(200).send({'rating': rating});
} 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({
@@ -24,11 +55,60 @@ routeRatingsRouter.get('/by/route/:id', async (req: Request, res: Response) => {
} }
}); });
/**
* @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) => { routeRatingsRouter.post('/', async (req: Request, res: Response) => {
try { try {
let route_id = req.query.route_id as string; let route_id = req.query.route_id as string;
let stars = Number(req.query.stars); let stars = Number(req.query.stars);
let captcha_token = req.query['h-captcha-response'] as string; let captcha_token = req.query['hcaptcha_response'] as string;
if (!route_id || isNaN(stars) || !captcha_token) { if (!route_id || isNaN(stars) || !captcha_token) {
res.status(400).send({'message': 'Missing parameters'}); res.status(400).send({'message': 'Missing parameters'});
@@ -48,7 +128,7 @@ routeRatingsRouter.post('/', async (req: Request, res: Response) => {
} else { } else {
res.status(500).send({}); res.status(500).send({});
} }
} 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({
@@ -7,11 +7,14 @@ import {RouteRating} from './RouteRating.interface';
* @return Promise<RouteRating[]> The ratings * @return Promise<RouteRating[]> The ratings
*/ */
export const findByRoute = async (route_id: string): Promise<RouteRating[]> => { export const findByRoute = async (route_id: string): Promise<RouteRating[]> => {
let conn = ClimbingRouteRatingDB.getConnection(); let conn = await ClimbingRouteRatingDB.getConnection();
try { try {
return await conn.query('SELECT rating_id, route_id, stars, timestamp FROM route_ratings WHERE route_id = ?', route_id); return await conn.query('SELECT rating_id, route_id, stars, timestamp FROM route_ratings WHERE route_id = ?', route_id);
} catch (err) { } catch (err) {
throw err; throw err;
} finally {
// Return connection
await conn.end();
} }
}; };
@@ -41,12 +44,15 @@ export const getStarsForRoute = async (route_id: string): Promise<number> => {
* @return number The id of the created rating * @return number The id of the created rating
*/ */
export const createRating = async (route_id: string, stars: number): Promise<number> => { export const createRating = async (route_id: string, stars: number): Promise<number> => {
let conn = ClimbingRouteRatingDB.getConnection(); let conn = await ClimbingRouteRatingDB.getConnection();
try { try {
let res = await conn.query('INSERT INTO route_ratings (route_id, stars) VALUES (?, ?) RETURNING rating_id', [route_id, stars]); let res = await conn.query('INSERT INTO route_ratings (route_id, stars) VALUES (?, ?) RETURNING rating_id', [route_id, stars]);
return res[0].comment_id; return res[0].comment_id;
} catch (err) { } catch (err) {
throw err; throw err;
} finally {
// Return connection
await conn.end();
} }
}; };
@@ -13,7 +13,7 @@ export namespace RaPlaChangesDB {
connectionLimit: 5 connectionLimit: 5
}); });
export function getConnection() { export const getConnection = async () => {
return pool; return pool.getConnection();
} };
} }
@@ -18,7 +18,7 @@ dhbwRaPlaChangesRouter.get('/', async (req: Request, res: Response) => {
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({
@@ -36,7 +36,7 @@ dhbwRaPlaChangesRouter.get('/:id', async (req: Request, res: Response) => {
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({
@@ -6,7 +6,7 @@ import {RaPlaChangesDB} from '../DHBWRaPlaChanges.db';
dotenv.config(); dotenv.config();
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 = await RaPlaChangesDB.getConnection();
try { try {
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]);
@@ -68,11 +68,14 @@ 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 {
// Return connection
await 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 = await RaPlaChangesDB.getConnection();
try { try {
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);
@@ -123,5 +126,8 @@ 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 {
// Return connection
await conn.end();
} }
}; };
@@ -17,7 +17,7 @@ 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({
@@ -13,7 +13,7 @@ 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({
@@ -27,7 +27,7 @@ generalInfoRouter.get('/', async (req: Request, res: Response) => {
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({
+4 -4
View File
@@ -20,10 +20,10 @@ export namespace PartyPlanerDB {
connectionLimit: 5 connectionLimit: 5
}); });
export function getConnection(useDev: boolean = false) { export const getConnection = async (useDev: boolean = false) => {
if (useDev) { if (useDev) {
return dev_pool; return dev_pool.getConnection();
}
return prod_pool;
} }
return prod_pool.getConnection();
};
} }
+1 -1
View File
@@ -29,7 +29,7 @@ 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({
+1 -2
View File
@@ -14,7 +14,6 @@ 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();
@@ -39,7 +38,7 @@ eventRouter.get('/:isDevCall', async (req: Request, res: Response) => {
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({
@@ -11,7 +11,7 @@ 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 = await PartyPlanerDB.getConnection(useDev);
try { try {
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);
@@ -69,5 +69,8 @@ export const getEventData = async (useDev: boolean, userId: string): Promise<Eve
return eventsList; return eventsList;
} catch (err) { } catch (err) {
throw err; throw err;
} finally {
// Return connection
await conn.end();
} }
}; };
@@ -38,7 +38,7 @@ friendshipRouter.get('/:isDevCall', async (req: Request, res: Response) => {
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({
@@ -11,7 +11,7 @@ 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 = await PartyPlanerDB.getConnection(useDev);
try { try {
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);
@@ -30,5 +30,8 @@ export const getFriendshipData = async (useDev: boolean, userId: string): Promis
return friends; return friends;
} catch (err) { } catch (err) {
throw err; throw err;
} finally {
// Return connection
await conn.end();
} }
}; };
@@ -38,7 +38,7 @@ inviteRouter.get('/:isDevCall', async (req: Request, res: Response) => {
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({
@@ -11,7 +11,7 @@ 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 = await PartyPlanerDB.getConnection(useDev);
try { try {
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);
@@ -37,5 +37,8 @@ export const getInvitesData = async (useDev: boolean, userId: string): Promise<R
return invites; return invites;
} catch (err) { } catch (err) {
throw err; throw err;
} finally {
// Return connection
await conn.end();
} }
}; };
+1 -1
View File
@@ -58,7 +58,7 @@ loginRouter.post('/:isDevCall', async (req: Request, res: Response) => {
let session = await UserService.loginUser(useDev, username, email, password, userIP, deviceInfo); 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({
@@ -77,7 +77,7 @@ registerRouter.post('/:isDevCall', async (req: Request, res: Response) => {
let session = await UserService.registerUser(useDev, username, email, firstName, lastName, password, userIP, deviceInfo); 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({
@@ -38,7 +38,7 @@ sessionRouter.get('/:isDevCall', async (req: Request, res: Response) => {
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({
@@ -11,7 +11,7 @@ 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 = await PartyPlanerDB.getConnection(useDev);
try { try {
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);
@@ -29,5 +29,8 @@ export const getSessionData = async (useDev: boolean, userId: string): Promise<S
return sessions; return sessions;
} catch (err) { } catch (err) {
throw err; throw err;
} finally {
// Return connection
await conn.end();
} }
}; };
+1 -1
View File
@@ -37,7 +37,7 @@ userRouter.get('/:isDevCall', async (req: Request, res: Response) => {
let data = await UserService.getUserData(useDev, userId); 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({
+24 -6
View File
@@ -15,7 +15,7 @@ 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 = await PartyPlanerDB.getConnection(useDev);
try { try {
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);
@@ -36,6 +36,9 @@ export const getUserData = async (useDev: boolean, userId: string): Promise<User
return user; return user;
} catch (err) { } catch (err) {
throw err; throw err;
} finally {
// Return connection
await conn.end();
} }
}; };
@@ -45,7 +48,7 @@ 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 = await PartyPlanerDB.getConnection(useDev);
try { try {
const rows = await conn.query('SELECT username, email FROM users'); const rows = await conn.query('SELECT username, email FROM users');
@@ -63,6 +66,9 @@ export const getExistingUsernamesAndEmails = async (useDev: boolean): Promise<an
}; };
} catch (err) { } catch (err) {
throw err; throw err;
} finally {
// Return connection
await conn.end();
} }
}; };
@@ -78,7 +84,7 @@ 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 = await PartyPlanerDB.getConnection(useDev);
try { try {
const pwHash = bcrypt.hashSync(password, 10); const pwHash = bcrypt.hashSync(password, 10);
const sessionKey = Guid.create().toString(); const sessionKey = Guid.create().toString();
@@ -125,6 +131,9 @@ export const registerUser = async (useDev: boolean, username: string, email: str
}; };
} catch (err) { } catch (err) {
throw err; throw err;
} finally {
// Return connection
await conn.end();
} }
}; };
@@ -138,7 +147,7 @@ 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 = await PartyPlanerDB.getConnection(useDev);
try { try {
let query_result; let query_result;
@@ -197,6 +206,9 @@ export const loginUser = async (useDev: boolean, username: string, email: string
} catch (err) { } catch (err) {
throw err; throw err;
} finally {
// Return connection
await conn.end();
} }
}; };
@@ -207,7 +219,7 @@ 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 = await PartyPlanerDB.getConnection(useDev);
try { try {
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 = ?';
@@ -254,11 +266,14 @@ export const checkUsernameAndEmail = async (useDev: boolean, username: string, e
} catch (err) { } catch (err) {
throw err; throw err;
} finally {
// Return connection
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 = PartyPlanerDB.getConnection(useDev); let conn = await PartyPlanerDB.getConnection(useDev);
try { try {
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]);
@@ -270,5 +285,8 @@ 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 {
// Return connection
await conn.end();
} }
}; };
@@ -26,7 +26,7 @@ export const raPlaMiddlewareRouter = express.Router();
* 400: * 400:
* description: Wrong parameters, see response body for detailed information * description: Wrong parameters, see response body for detailed information
* 500: * 500:
* description: A server error occured. Please try again. If this issue persists, contact the admin. * description: A server error occurred. Please try again. If this issue persists, contact the admin.
* parameters: * parameters:
* - in: query * - in: query
* name: user * name: user
@@ -34,30 +34,35 @@ export const raPlaMiddlewareRouter = express.Router();
* description: The user from RaPla, can be taken directly from the RaPla link * description: The user from RaPla, can be taken directly from the RaPla link
* schema: * schema:
* type: string * type: string
* example: mueller
* - in: query * - in: query
* name: file * name: file
* required: true * required: true
* description: The file from RaPla, can be taken directly from the RaPla link * description: The file from RaPla, can be taken directly from the RaPla link
* schema: * schema:
* type: string * type: string
* example: TINF19B4
* - in: query * - in: query
* name: blockers * name: blockers
* required: false * required: false
* description: Whether to remove blockers from the .ics file * description: Whether to remove blockers from the .ics file
* schema: * schema:
* type: boolean [0,1] * type: boolean
* example: 1
* - in: query * - in: query
* name: wahl * name: wahl
* required: false * required: false
* description: The chosen elective module which is not to be filtered out * description: The chosen elective module which is not to be filtered out
* schema: * schema:
* type: number * type: integer
* example: 0
* - in: query * - in: query
* name: pflicht * name: pflicht
* required: false * required: false
* description: The chosen profile module which is not to be filtered out * description: The chosen profile module which is not to be filtered out
* schema: * schema:
* type: number * type: integer
* example: 2
*/ */
raPlaMiddlewareRouter.get('/', async (req: Request, res: Response) => { raPlaMiddlewareRouter.get('/', async (req: Request, res: Response) => {
try { try {
@@ -81,7 +86,7 @@ raPlaMiddlewareRouter.get('/', async (req: Request, res: Response) => {
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({
@@ -153,7 +153,11 @@ export const removeElective = function (ical: iCalFile, chosenElective: string):
{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'},
{name: 'Psychologische Grundlagen für Informatiker'},
{name: 'Erklärbare Künstliche Intelligenz'},
{name: 'Innovation Management'}
]; ];
electiveToRemove.splice(parseInt(chosenElective), 1); electiveToRemove.splice(parseInt(chosenElective), 1);
@@ -13,7 +13,7 @@ export namespace HighlightMarkerDB {
connectionLimit: 5 connectionLimit: 5
}); });
export function getConnection() { export const getConnection = async () => {
return pool; return pool.getConnection();
} };
} }
@@ -16,7 +16,7 @@ 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({
@@ -14,7 +14,7 @@ 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({
@@ -45,7 +45,7 @@ addHighlightRouter.post('/', (req: Request, res: Response) => {
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({
@@ -8,7 +8,7 @@ dotenv.config();
* @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 = await HighlightMarkerDB.getConnection();
try { try {
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 +24,8 @@ 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 {
// Return connection
await conn.end();
} }
}; };
+3
View File
@@ -0,0 +1,3 @@
test('Test template', async () => {
expect(true).toBe(true);
});
+1 -3
View File
@@ -5,8 +5,6 @@
"outDir": "./dist", "outDir": "./dist",
"strict": true, "strict": true,
"esModuleInterop": true, "esModuleInterop": true,
"inlineSourceMap": true, "inlineSourceMap": true
"experimentalDecorators": true,
"emitDecoratorMetadata": true
} }
} }
-8
View File
@@ -1,8 +0,0 @@
{
"entryFile": "app.ts",
"noImplicitAdditionalProperties": "throw-on-extras",
"spec": {
"outputDirectory": ".",
"specVersion": 3
}
}