Compare commits
127 Commits
a79bed259b
...
v0.0.8
| Author | SHA1 | Date | |
|---|---|---|---|
| d948fe2631 | |||
| 2b5525323b | |||
| b57fde9b0a | |||
| 86706f9422 | |||
| 0687f268fc | |||
| bc426831db | |||
| 276e553e13 | |||
| e7ab302c61 | |||
| a5d70ce4b5 | |||
| d67be313e6 | |||
| 15d2d029dc | |||
| b6ea5e6549 | |||
| f378b0651a | |||
| 1a0573e0d0 | |||
| 9f103d8df1 | |||
| daa899a1ef | |||
| 59cb72a11d | |||
| 28c1b6d31d | |||
| dcb791c9a2 | |||
| 907259bf73 | |||
| 02f7ddbb37 | |||
| 63b1ca9b56 | |||
| 39857cf6e6 | |||
| 3090ae69f3 | |||
| 92186a86cc | |||
| 97e8470b0d | |||
| 6b0e3503a7 | |||
| 1e2de7656e | |||
| 56c6a7efb0 | |||
| 9c4e54fc6e | |||
| 2c47436259 | |||
| 9b5d16ae92 | |||
| deb13674b2 | |||
| 17c82ff409 | |||
| f9e314bf9f | |||
| e4c1930dd1 | |||
| b337ab424d | |||
| 82a0e194cb | |||
| 599296c4e3 | |||
| 2594a607dc | |||
| 335d4e24da | |||
| becc277123 | |||
| 52cdd41ec8 | |||
| 53548ba7a6 | |||
| 1dc438beb2 | |||
| c9ba69792f | |||
| ab67e5f4aa | |||
| 557608e318 | |||
| a83fedc9b8 | |||
| 61a17b198f | |||
| 3df1db4ad8 | |||
| e46cfa0d77 | |||
| 4126d31a5e | |||
| 9d9549cdd4 | |||
| eb40de6eb4 | |||
| 6efd09db73 | |||
| 3f09e3d387 | |||
| 05868e0e00 | |||
| 580a73f9a5 | |||
| ab7110d49f | |||
| 875781335c | |||
| 625340cf8a | |||
| 8d9dbc3957 | |||
| 07d813082b | |||
| a684f60252 | |||
| 931cae3c98 | |||
| dfd82a6293 | |||
| 82d4b11de3 | |||
| 75473937cf | |||
| a68bbab8ab | |||
| 5cfd2c9a52 | |||
| 6c7b31d76c | |||
| 2924ac2900 | |||
| a501625dd6 | |||
| cc64ce4498 | |||
| c9378e6cae | |||
| 62c7f26540 | |||
| 18e3ef9a79 | |||
| 395b0101a8 | |||
| 84a0bd2cd9 | |||
| 9cd181c5b8 | |||
| 41828a6e41 | |||
| 356e398caf | |||
| 6cb978df98 | |||
| 4cb0efa6bd | |||
| e0fa58da57 | |||
| 5d31d8d1a2 | |||
| 53a01ad977 | |||
| d7791756dc | |||
| dd48ee2f7e | |||
| ec64ec3d63 | |||
| 35dbfeb5e7 | |||
| a9ecfccfd2 | |||
| d850650aeb | |||
| 43e256f38c | |||
| b5f9cf201d | |||
| 6e121a3ce2 | |||
| 555e37eaf7 | |||
| 9675e79441 | |||
| 345851bf1d | |||
| 7c5a3893ef | |||
| b53b5cf91f | |||
| 04813173e4 | |||
| c4270b0839 | |||
| bb24ed53a4 | |||
| 1b74b21420 | |||
| b7cbe2a0b4 | |||
| 500b94b44a | |||
| 641466a731 | |||
| e3ea83bb47 | |||
| b6043744a9 | |||
| 2b38044271 | |||
| 4c3d2643c1 | |||
| e2cc0c0b80 | |||
| ce55dce011 | |||
| a738c19316 | |||
| 63b8176bdf | |||
| bc76afafce | |||
| 1f49ad43a1 | |||
| 6a762f570d | |||
| 1b7424f750 | |||
| bdd4f705be | |||
| ded14b1b3b | |||
| fbd3f615ad | |||
| a22a7a19c2 | |||
| 2d263814db | |||
| cc5d90cb4f |
54
.drone.yml
54
.drone.yml
@@ -37,11 +37,23 @@ steps:
|
||||
tags:
|
||||
- dev
|
||||
registry: registry.odit.services
|
||||
when:
|
||||
branch:
|
||||
- dev
|
||||
event:
|
||||
- push
|
||||
- name: run full license export
|
||||
depends_on: ["clone"]
|
||||
image: node:alpine
|
||||
commands:
|
||||
- yarn
|
||||
- yarn licenses:export
|
||||
- name: push new licenses file to repo
|
||||
depends_on: ["run full license export"]
|
||||
image: appleboy/drone-git-push
|
||||
settings:
|
||||
branch: dev
|
||||
commit: true
|
||||
commit_message: new license file version [CI SKIP]
|
||||
author_email: bot@odit.services
|
||||
remote: git@git.odit.services:lfk/backend.git
|
||||
ssh_key:
|
||||
from_secret: GITLAB_SSHKEY
|
||||
|
||||
trigger:
|
||||
branch:
|
||||
@@ -90,32 +102,20 @@ steps:
|
||||
from_secret: DOCKER_REGISTRY_PASSWORD
|
||||
repo: registry.odit.services/lfk/backend
|
||||
tags:
|
||||
- $DRONE_TAG
|
||||
- '${DRONE_TAG}'
|
||||
registry: registry.odit.services
|
||||
- name: trigger js lib build
|
||||
depends_on: [clone]
|
||||
image: plugins/downstream
|
||||
settings:
|
||||
server: https://ci.odit.services/
|
||||
token:
|
||||
from_secret: BOT_DRONE_KEY
|
||||
fork: false
|
||||
repositories:
|
||||
- lfk/lfk-client-js
|
||||
params:
|
||||
- SOURCE_TAG=$DRONE_TAG
|
||||
- name: trigger node lib build
|
||||
depends_on: [clone]
|
||||
image: plugins/downstream
|
||||
image: idcooldi/drone-webhook
|
||||
settings:
|
||||
server: https://ci.odit.services/
|
||||
token:
|
||||
urls: https://ci.odit.services/api/repos/lfk/lfk-client-node/builds?SOURCE_TAG=${DRONE_TAG}
|
||||
bearer:
|
||||
from_secret: BOT_DRONE_KEY
|
||||
- name: trigger js lib build
|
||||
image: idcooldi/drone-webhook
|
||||
settings:
|
||||
urls: https://ci.odit.services/api/repos/lfk/lfk-client-js/builds?SOURCE_TAG=${DRONE_TAG}
|
||||
bearer:
|
||||
from_secret: BOT_DRONE_KEY
|
||||
fork: false
|
||||
repositories:
|
||||
- lfk/lfk-client-node
|
||||
params:
|
||||
- SOURCE_TAG=$DRONE_TAG
|
||||
trigger:
|
||||
event:
|
||||
- tag
|
||||
3
.gitignore
vendored
3
.gitignore
vendored
@@ -133,4 +133,5 @@ build
|
||||
*.sqlite
|
||||
*.sqlite-jurnal
|
||||
/docs
|
||||
lib
|
||||
lib
|
||||
/oss-attribution
|
||||
1296
licenses.md
Normal file
1296
licenses.md
Normal file
File diff suppressed because it is too large
Load Diff
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@odit/lfk-backend",
|
||||
"version": "0.0.5",
|
||||
"version": "0.0.8",
|
||||
"main": "src/app.ts",
|
||||
"repository": "https://git.odit.services/lfk/backend",
|
||||
"author": {
|
||||
@@ -48,6 +48,7 @@
|
||||
"validator": "^13.5.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@odit/license-exporter": "^0.0.8",
|
||||
"@types/cors": "^2.8.8",
|
||||
"@types/csvtojson": "^1.1.5",
|
||||
"@types/express": "^4.17.9",
|
||||
@@ -74,7 +75,8 @@
|
||||
"test:watch": "jest --watchAll",
|
||||
"test:ci": "start-server-and-test dev http://localhost:4010/api/docs/openapi.json test",
|
||||
"seed": "ts-node ./node_modules/typeorm/cli.js schema:sync && ts-node ./node_modules/typeorm-seeding/dist/cli.js seed",
|
||||
"openapi:export": "ts-node src/openapi_export.ts"
|
||||
"openapi:export": "ts-node scripts/openapi_export.ts",
|
||||
"licenses:export": "license-exporter --md"
|
||||
},
|
||||
"nodemonConfig": {
|
||||
"ignore": [
|
||||
|
||||
@@ -4,9 +4,9 @@ import fs from "fs";
|
||||
import "reflect-metadata";
|
||||
import { createExpressServer, getMetadataArgsStorage } from "routing-controllers";
|
||||
import { routingControllersToSpec } from 'routing-controllers-openapi';
|
||||
import authchecker from "./authchecker";
|
||||
import { config } from './config';
|
||||
import { ErrorHandler } from './middlewares/ErrorHandler';
|
||||
import { config } from '../src/config';
|
||||
import authchecker from "../src/middlewares/authchecker";
|
||||
import { ErrorHandler } from '../src/middlewares/ErrorHandler';
|
||||
|
||||
const CONTROLLERS_FILE_EXTENSION = process.env.NODE_ENV === 'production' ? 'js' : 'ts';
|
||||
createExpressServer({
|
||||
@@ -15,7 +15,7 @@ createExpressServer({
|
||||
development: config.development,
|
||||
cors: true,
|
||||
routePrefix: "/api",
|
||||
controllers: [`${__dirname}/controllers/*.${CONTROLLERS_FILE_EXTENSION}`],
|
||||
controllers: [`${__dirname}/../src/controllers/*.${CONTROLLERS_FILE_EXTENSION}`],
|
||||
});
|
||||
|
||||
const storage = getMetadataArgsStorage();
|
||||
@@ -44,13 +44,18 @@ const spec = routingControllersToSpec(
|
||||
"in": "cookie",
|
||||
"name": "lfk_backend__refresh_token",
|
||||
description: "A cookie containing a JWT based refreh token. Attention: Doesn't work in swagger-ui. Use /api/auth/login or /api/auth/refresh to get one."
|
||||
},
|
||||
"StatsApiToken": {
|
||||
"type": "http",
|
||||
"scheme": "bearer",
|
||||
description: "Api token that can be obtained by creating a new stats client (post to /api/statsclients)."
|
||||
}
|
||||
}
|
||||
},
|
||||
info: {
|
||||
description: "The the backend API for the LfK! runner system.",
|
||||
title: "LfK! Backend API",
|
||||
version: "0.0.5",
|
||||
version: "0.0.8",
|
||||
},
|
||||
}
|
||||
);
|
||||
@@ -1,9 +1,9 @@
|
||||
import consola from "consola";
|
||||
import "reflect-metadata";
|
||||
import { createExpressServer } from "routing-controllers";
|
||||
import authchecker from "./authchecker";
|
||||
import { config, e as errors } from './config';
|
||||
import loaders from "./loaders/index";
|
||||
import authchecker from "./middlewares/authchecker";
|
||||
import { ErrorHandler } from './middlewares/ErrorHandler';
|
||||
|
||||
const CONTROLLERS_FILE_EXTENSION = process.env.NODE_ENV === 'production' ? 'js' : 'ts';
|
||||
|
||||
@@ -70,7 +70,6 @@ export class AuthController {
|
||||
if (refresh_token && refresh_token.length != 0 && refreshAuth.token == undefined) {
|
||||
refreshAuth.token = refresh_token;
|
||||
}
|
||||
console.log(req.headers)
|
||||
let auth;
|
||||
try {
|
||||
auth = await refreshAuth.toAuth();
|
||||
|
||||
105
src/controllers/DonorController.ts
Normal file
105
src/controllers/DonorController.ts
Normal file
@@ -0,0 +1,105 @@
|
||||
import { Authorized, Body, Delete, Get, JsonController, OnUndefined, Param, Post, Put, QueryParam } from 'routing-controllers';
|
||||
import { OpenAPI, ResponseSchema } from 'routing-controllers-openapi';
|
||||
import { getConnectionManager, Repository } from 'typeorm';
|
||||
import { DonorIdsNotMatchingError, DonorNotFoundError } from '../errors/DonorErrors';
|
||||
import { CreateDonor } from '../models/actions/CreateDonor';
|
||||
import { UpdateDonor } from '../models/actions/UpdateDonor';
|
||||
import { Donor } from '../models/entities/Donor';
|
||||
import { ResponseDonor } from '../models/responses/ResponseDonor';
|
||||
import { ResponseEmpty } from '../models/responses/ResponseEmpty';
|
||||
|
||||
@JsonController('/donors')
|
||||
@OpenAPI({ security: [{ "AuthToken": [] }, { "RefreshTokenCookie": [] }] })
|
||||
export class DonorController {
|
||||
private donorRepository: Repository<Donor>;
|
||||
|
||||
/**
|
||||
* Gets the repository of this controller's model/entity.
|
||||
*/
|
||||
constructor() {
|
||||
this.donorRepository = getConnectionManager().get().getRepository(Donor);
|
||||
}
|
||||
|
||||
@Get()
|
||||
@Authorized("DONOR:GET")
|
||||
@ResponseSchema(ResponseDonor, { isArray: true })
|
||||
@OpenAPI({ description: 'Lists all runners from all teams/orgs. <br> This includes the runner\'s group and distance ran.' })
|
||||
async getAll() {
|
||||
let responseDonors: ResponseDonor[] = new Array<ResponseDonor>();
|
||||
const donors = await this.donorRepository.find();
|
||||
donors.forEach(donor => {
|
||||
responseDonors.push(new ResponseDonor(donor));
|
||||
});
|
||||
return responseDonors;
|
||||
}
|
||||
|
||||
@Get('/:id')
|
||||
@Authorized("DONOR:GET")
|
||||
@ResponseSchema(ResponseDonor)
|
||||
@ResponseSchema(DonorNotFoundError, { statusCode: 404 })
|
||||
@OnUndefined(DonorNotFoundError)
|
||||
@OpenAPI({ description: 'Lists all information about the runner whose id got provided.' })
|
||||
async getOne(@Param('id') id: number) {
|
||||
let donor = await this.donorRepository.findOne({ id: id })
|
||||
if (!donor) { throw new DonorNotFoundError(); }
|
||||
return new ResponseDonor(donor);
|
||||
}
|
||||
|
||||
@Post()
|
||||
@Authorized("DONOR:CREATE")
|
||||
@ResponseSchema(ResponseDonor)
|
||||
@OpenAPI({ description: 'Create a new runner. <br> Please remeber to provide the runner\'s group\'s id.' })
|
||||
async post(@Body({ validate: true }) createRunner: CreateDonor) {
|
||||
let donor;
|
||||
try {
|
||||
donor = await createRunner.toDonor();
|
||||
} catch (error) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
donor = await this.donorRepository.save(donor)
|
||||
return new ResponseDonor(await this.donorRepository.findOne(donor));
|
||||
}
|
||||
|
||||
@Put('/:id')
|
||||
@Authorized("DONOR:UPDATE")
|
||||
@ResponseSchema(ResponseDonor)
|
||||
@ResponseSchema(DonorNotFoundError, { statusCode: 404 })
|
||||
@ResponseSchema(DonorIdsNotMatchingError, { statusCode: 406 })
|
||||
@OpenAPI({ description: "Update the runner whose id you provided. <br> Please remember that ids can't be changed." })
|
||||
async put(@Param('id') id: number, @Body({ validate: true }) donor: UpdateDonor) {
|
||||
let oldDonor = await this.donorRepository.findOne({ id: id });
|
||||
|
||||
if (!oldDonor) {
|
||||
throw new DonorNotFoundError();
|
||||
}
|
||||
|
||||
if (oldDonor.id != donor.id) {
|
||||
throw new DonorIdsNotMatchingError();
|
||||
}
|
||||
|
||||
await this.donorRepository.save(await donor.updateDonor(oldDonor));
|
||||
return new ResponseDonor(await this.donorRepository.findOne({ id: id }));
|
||||
}
|
||||
|
||||
@Delete('/:id')
|
||||
@Authorized("DONOR:DELETE")
|
||||
@ResponseSchema(ResponseDonor)
|
||||
@ResponseSchema(ResponseEmpty, { statusCode: 204 })
|
||||
@OnUndefined(204)
|
||||
@OpenAPI({ description: 'Delete the runner whose id you provided. <br> If no runner with this id exists it will just return 204(no content).' })
|
||||
async remove(@Param("id") id: number, @QueryParam("force") force: boolean) {
|
||||
let donor = await this.donorRepository.findOne({ id: id });
|
||||
if (!donor) { return null; }
|
||||
const responseDonor = await this.donorRepository.findOne(donor);
|
||||
|
||||
if (!donor) {
|
||||
throw new DonorNotFoundError();
|
||||
}
|
||||
|
||||
//TODO: DELETE DONATIONS AND WARN FOR FORCE (https://git.odit.services/lfk/backend/issues/66)
|
||||
|
||||
await this.donorRepository.delete(donor);
|
||||
return new ResponseDonor(responseDonor);
|
||||
}
|
||||
}
|
||||
75
src/controllers/StatsClientController.ts
Normal file
75
src/controllers/StatsClientController.ts
Normal file
@@ -0,0 +1,75 @@
|
||||
import { Authorized, Body, Delete, Get, JsonController, OnUndefined, Param, Post } from 'routing-controllers';
|
||||
import { OpenAPI, ResponseSchema } from 'routing-controllers-openapi';
|
||||
import { getConnectionManager, Repository } from 'typeorm';
|
||||
import { StatsClientNotFoundError } from '../errors/StatsClientErrors';
|
||||
import { TrackNotFoundError } from "../errors/TrackErrors";
|
||||
import { CreateStatsClient } from '../models/actions/CreateStatsClient';
|
||||
import { StatsClient } from '../models/entities/StatsClient';
|
||||
import { ResponseEmpty } from '../models/responses/ResponseEmpty';
|
||||
import { ResponseStatsClient } from '../models/responses/ResponseStatsClient';
|
||||
|
||||
@JsonController('/statsclients')
|
||||
@OpenAPI({ security: [{ "AuthToken": [] }, { "RefreshTokenCookie": [] }] })
|
||||
export class StatsClientController {
|
||||
private clientRepository: Repository<StatsClient>;
|
||||
|
||||
/**
|
||||
* Gets the repository of this controller's model/entity.
|
||||
*/
|
||||
constructor() {
|
||||
this.clientRepository = getConnectionManager().get().getRepository(StatsClient);
|
||||
}
|
||||
|
||||
@Get()
|
||||
@Authorized("STATSCLIENT:GET")
|
||||
@ResponseSchema(ResponseStatsClient, { isArray: true })
|
||||
@OpenAPI({ description: 'Lists all stats clients. Please remember that the key can only be viewed on creation.' })
|
||||
async getAll() {
|
||||
let responseClients: ResponseStatsClient[] = new Array<ResponseStatsClient>();
|
||||
const clients = await this.clientRepository.find();
|
||||
clients.forEach(clients => {
|
||||
responseClients.push(new ResponseStatsClient(clients));
|
||||
});
|
||||
return responseClients;
|
||||
}
|
||||
|
||||
@Get('/:id')
|
||||
@Authorized("STATSCLIENT:GET")
|
||||
@ResponseSchema(ResponseStatsClient)
|
||||
@ResponseSchema(StatsClientNotFoundError, { statusCode: 404 })
|
||||
@OnUndefined(StatsClientNotFoundError)
|
||||
@OpenAPI({ description: "Lists all information about the stats client whose id got provided. Please remember that the key can only be viewed on creation." })
|
||||
async getOne(@Param('id') id: number) {
|
||||
let client = await this.clientRepository.findOne({ id: id });
|
||||
if (!client) { throw new TrackNotFoundError(); }
|
||||
return new ResponseStatsClient(client);
|
||||
}
|
||||
|
||||
@Post()
|
||||
@Authorized("STATSCLIENT:CREATE")
|
||||
@ResponseSchema(ResponseStatsClient)
|
||||
@OpenAPI({ description: "Create a new stats client. <br> Please remember that the client\'s key will be generated automaticly and that it can only be viewed on creation." })
|
||||
async post(
|
||||
@Body({ validate: true })
|
||||
client: CreateStatsClient
|
||||
) {
|
||||
let newClient = await this.clientRepository.save(await client.toStatsClient());
|
||||
let responseClient = new ResponseStatsClient(newClient);
|
||||
responseClient.key = newClient.cleartextkey;
|
||||
return responseClient;
|
||||
}
|
||||
|
||||
@Delete('/:id')
|
||||
@Authorized("STATSCLIENT:DELETE")
|
||||
@ResponseSchema(ResponseStatsClient)
|
||||
@ResponseSchema(ResponseEmpty, { statusCode: 204 })
|
||||
@OnUndefined(204)
|
||||
@OpenAPI({ description: "Delete the stats client whose id you provided. <br> If no client with this id exists it will just return 204(no content)." })
|
||||
async remove(@Param("id") id: number) {
|
||||
let client = await this.clientRepository.findOne({ id: id });
|
||||
if (!client) { return null; }
|
||||
|
||||
await this.clientRepository.delete(client);
|
||||
return new ResponseStatsClient(client);
|
||||
}
|
||||
}
|
||||
124
src/controllers/StatsController.ts
Normal file
124
src/controllers/StatsController.ts
Normal file
@@ -0,0 +1,124 @@
|
||||
import { Get, JsonController, UseBefore } from 'routing-controllers';
|
||||
import { OpenAPI, ResponseSchema } from 'routing-controllers-openapi';
|
||||
import { getConnection } from 'typeorm';
|
||||
import StatsAuth from '../middlewares/StatsAuth';
|
||||
import { Donation } from '../models/entities/Donation';
|
||||
import { Runner } from '../models/entities/Runner';
|
||||
import { RunnerOrganisation } from '../models/entities/RunnerOrganisation';
|
||||
import { RunnerTeam } from '../models/entities/RunnerTeam';
|
||||
import { Scan } from '../models/entities/Scan';
|
||||
import { User } from '../models/entities/User';
|
||||
import { ResponseStats } from '../models/responses/ResponseStats';
|
||||
import { ResponseStatsOrgnisation } from '../models/responses/ResponseStatsOrganisation';
|
||||
import { ResponseStatsRunner } from '../models/responses/ResponseStatsRunner';
|
||||
import { ResponseStatsTeam } from '../models/responses/ResponseStatsTeam';
|
||||
|
||||
@JsonController('/stats')
|
||||
export class StatsController {
|
||||
|
||||
@Get()
|
||||
@ResponseSchema(ResponseStats)
|
||||
@OpenAPI({ description: "A very basic stats endpoint providing basic counters for a dashboard or simmilar" })
|
||||
async get() {
|
||||
let connection = getConnection();
|
||||
let runners = await connection.getRepository(Runner).find({ relations: ['scans', 'scans.track'] });
|
||||
let teams = await connection.getRepository(RunnerTeam).find();
|
||||
let orgs = await connection.getRepository(RunnerOrganisation).find();
|
||||
let users = await connection.getRepository(User).find();
|
||||
let scans = await connection.getRepository(Scan).find();
|
||||
let donations = await connection.getRepository(Donation).find({ relations: ['runner', 'runner.scans', 'runner.scans.track'] });
|
||||
return new ResponseStats(runners, teams, orgs, users, scans, donations)
|
||||
}
|
||||
|
||||
@Get("/runners/distance")
|
||||
@UseBefore(StatsAuth)
|
||||
@ResponseSchema(ResponseStatsRunner, { isArray: true })
|
||||
@OpenAPI({ description: "Returns the top ten runners by distance.", security: [{ "StatsApiToken": [] }, { "AuthToken": [] }, { "RefreshTokenCookie": [] }] })
|
||||
async getTopRunnersByDistance() {
|
||||
let runners = await getConnection().getRepository(Runner).find({ relations: ['scans', 'group', 'distanceDonations', 'scans.track'] });
|
||||
let topRunners = runners.sort((runner1, runner2) => runner1.distance - runner2.distance).slice(0, 9);
|
||||
let responseRunners: ResponseStatsRunner[] = new Array<ResponseStatsRunner>();
|
||||
topRunners.forEach(runner => {
|
||||
responseRunners.push(new ResponseStatsRunner(runner));
|
||||
});
|
||||
return responseRunners;
|
||||
}
|
||||
|
||||
@Get("/runners/donations")
|
||||
@UseBefore(StatsAuth)
|
||||
@ResponseSchema(ResponseStatsRunner, { isArray: true })
|
||||
@OpenAPI({ description: "Returns the top ten runners by donations.", security: [{ "StatsApiToken": [] }, { "AuthToken": [] }, { "RefreshTokenCookie": [] }] })
|
||||
async getTopRunnersByDonations() {
|
||||
let runners = await getConnection().getRepository(Runner).find({ relations: ['scans', 'group', 'distanceDonations', 'scans.track'] });
|
||||
let topRunners = runners.sort((runner1, runner2) => runner1.distanceDonationAmount - runner2.distanceDonationAmount).slice(0, 9);
|
||||
let responseRunners: ResponseStatsRunner[] = new Array<ResponseStatsRunner>();
|
||||
topRunners.forEach(runner => {
|
||||
responseRunners.push(new ResponseStatsRunner(runner));
|
||||
});
|
||||
return responseRunners;
|
||||
}
|
||||
|
||||
@Get("/scans")
|
||||
@UseBefore(StatsAuth)
|
||||
@ResponseSchema(ResponseStatsRunner, { isArray: true })
|
||||
@OpenAPI({ description: "Returns the top ten fastest track times (with their runner and the runner's group).", security: [{ "StatsApiToken": [] }, { "AuthToken": [] }, { "RefreshTokenCookie": [] }] })
|
||||
async getTopRunnersByTrackTime() {
|
||||
throw new Error("Not implemented yet.")
|
||||
}
|
||||
|
||||
@Get("/teams/distance")
|
||||
@UseBefore(StatsAuth)
|
||||
@ResponseSchema(ResponseStatsTeam, { isArray: true })
|
||||
@OpenAPI({ description: "Returns the top ten teams by distance.", security: [{ "StatsApiToken": [] }, { "AuthToken": [] }, { "RefreshTokenCookie": [] }] })
|
||||
async getTopTeamsByDistance() {
|
||||
let teams = await getConnection().getRepository(RunnerTeam).find({ relations: ['runners', 'runners.scans', 'runners.distanceDonations', 'runners.scans.track'] });
|
||||
let topTeams = teams.sort((team1, team2) => team1.distance - team2.distance).slice(0, 9);
|
||||
let responseTeams: ResponseStatsTeam[] = new Array<ResponseStatsTeam>();
|
||||
topTeams.forEach(team => {
|
||||
responseTeams.push(new ResponseStatsTeam(team));
|
||||
});
|
||||
return responseTeams;
|
||||
}
|
||||
|
||||
@Get("/teams/donations")
|
||||
@UseBefore(StatsAuth)
|
||||
@ResponseSchema(ResponseStatsTeam, { isArray: true })
|
||||
@OpenAPI({ description: "Returns the top ten teams by donations.", security: [{ "StatsApiToken": [] }, { "AuthToken": [] }, { "RefreshTokenCookie": [] }] })
|
||||
async getTopTeamsByDonations() {
|
||||
let teams = await getConnection().getRepository(RunnerTeam).find({ relations: ['runners', 'runners.scans', 'runners.distanceDonations', 'runners.scans.track'] });
|
||||
let topTeams = teams.sort((team1, team2) => team1.distanceDonationAmount - team2.distanceDonationAmount).slice(0, 9);
|
||||
let responseTeams: ResponseStatsTeam[] = new Array<ResponseStatsTeam>();
|
||||
topTeams.forEach(team => {
|
||||
responseTeams.push(new ResponseStatsTeam(team));
|
||||
});
|
||||
return responseTeams;
|
||||
}
|
||||
|
||||
@Get("/organisations/distance")
|
||||
@UseBefore(StatsAuth)
|
||||
@ResponseSchema(ResponseStatsOrgnisation, { isArray: true })
|
||||
@OpenAPI({ description: "Returns the top ten organisations by distance.", security: [{ "StatsApiToken": [] }, { "AuthToken": [] }, { "RefreshTokenCookie": [] }] })
|
||||
async getTopOrgsByDistance() {
|
||||
let orgs = await getConnection().getRepository(RunnerOrganisation).find({ relations: ['runners', 'runners.scans', 'runners.distanceDonations', 'runners.scans.track', 'teams', 'teams.runners', 'teams.runners.scans', 'teams.runners.distanceDonations', 'teams.runners.scans.track'] });
|
||||
let topOrgs = orgs.sort((org1, org2) => org1.distance - org2.distance).slice(0, 9);
|
||||
let responseOrgs: ResponseStatsOrgnisation[] = new Array<ResponseStatsOrgnisation>();
|
||||
topOrgs.forEach(org => {
|
||||
responseOrgs.push(new ResponseStatsOrgnisation(org));
|
||||
});
|
||||
return responseOrgs;
|
||||
}
|
||||
|
||||
@Get("/organisations/donations")
|
||||
@UseBefore(StatsAuth)
|
||||
@ResponseSchema(ResponseStatsOrgnisation, { isArray: true })
|
||||
@OpenAPI({ description: "Returns the top ten organisations by donations.", security: [{ "StatsApiToken": [] }, { "AuthToken": [] }, { "RefreshTokenCookie": [] }] })
|
||||
async getTopOrgsByDonations() {
|
||||
let orgs = await getConnection().getRepository(RunnerOrganisation).find({ relations: ['runners', 'runners.scans', 'runners.distanceDonations', 'runners.scans.track', 'teams', 'teams.runners', 'teams.runners.scans', 'teams.runners.distanceDonations', 'teams.runners.scans.track'] });
|
||||
let topOrgs = orgs.sort((org1, org2) => org1.distanceDonationAmount - org2.distanceDonationAmount).slice(0, 9);
|
||||
let responseOrgs: ResponseStatsOrgnisation[] = new Array<ResponseStatsOrgnisation>();
|
||||
topOrgs.forEach(org => {
|
||||
responseOrgs.push(new ResponseStatsOrgnisation(org));
|
||||
});
|
||||
return responseOrgs;
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,9 @@
|
||||
import { Authorized, Body, Delete, Get, JsonController, OnUndefined, Param, Post, Put } from 'routing-controllers';
|
||||
import { OpenAPI, ResponseSchema } from 'routing-controllers-openapi';
|
||||
import { getConnectionManager, Repository } from 'typeorm';
|
||||
import { EntityFromBody } from 'typeorm-routing-controllers-extensions';
|
||||
import { TrackIdsNotMatchingError, TrackNotFoundError } from "../errors/TrackErrors";
|
||||
import { TrackIdsNotMatchingError, TrackLapTimeCantBeNegativeError, TrackNotFoundError } from "../errors/TrackErrors";
|
||||
import { CreateTrack } from '../models/actions/CreateTrack';
|
||||
import { UpdateTrack } from '../models/actions/UpdateTrack';
|
||||
import { Track } from '../models/entities/Track';
|
||||
import { ResponseEmpty } from '../models/responses/ResponseEmpty';
|
||||
import { ResponseTrack } from '../models/responses/ResponseTrack';
|
||||
@@ -48,6 +48,7 @@ export class TrackController {
|
||||
@Post()
|
||||
@Authorized("TRACK:CREATE")
|
||||
@ResponseSchema(ResponseTrack)
|
||||
@ResponseSchema(TrackLapTimeCantBeNegativeError, { statusCode: 406 })
|
||||
@OpenAPI({ description: "Create a new track. <br> Please remember that the track\'s distance must be greater than 0." })
|
||||
async post(
|
||||
@Body({ validate: true })
|
||||
@@ -61,20 +62,21 @@ export class TrackController {
|
||||
@ResponseSchema(ResponseTrack)
|
||||
@ResponseSchema(TrackNotFoundError, { statusCode: 404 })
|
||||
@ResponseSchema(TrackIdsNotMatchingError, { statusCode: 406 })
|
||||
@ResponseSchema(TrackLapTimeCantBeNegativeError, { statusCode: 406 })
|
||||
@OpenAPI({ description: "Update the track whose id you provided. <br> Please remember that ids can't be changed." })
|
||||
async put(@Param('id') id: number, @EntityFromBody() track: Track) {
|
||||
async put(@Param('id') id: number, @Body({ validate: true }) updateTrack: UpdateTrack) {
|
||||
let oldTrack = await this.trackRepository.findOne({ id: id });
|
||||
|
||||
if (!oldTrack) {
|
||||
throw new TrackNotFoundError();
|
||||
}
|
||||
|
||||
if (oldTrack.id != track.id) {
|
||||
if (oldTrack.id != updateTrack.id) {
|
||||
throw new TrackIdsNotMatchingError();
|
||||
}
|
||||
await this.trackRepository.save(await updateTrack.updateTrack(oldTrack));
|
||||
|
||||
await this.trackRepository.save(track);
|
||||
return new ResponseTrack(track);
|
||||
return new ResponseTrack(await this.trackRepository.findOne({ id: id }));
|
||||
}
|
||||
|
||||
@Delete('/:id')
|
||||
|
||||
36
src/errors/DonorErrors.ts
Normal file
36
src/errors/DonorErrors.ts
Normal file
@@ -0,0 +1,36 @@
|
||||
import { IsString } from 'class-validator';
|
||||
import { NotAcceptableError, NotFoundError } from 'routing-controllers';
|
||||
|
||||
/**
|
||||
* Error to throw when a donor couldn't be found.
|
||||
*/
|
||||
export class DonorNotFoundError extends NotFoundError {
|
||||
@IsString()
|
||||
name = "DonorNotFoundError"
|
||||
|
||||
@IsString()
|
||||
message = "Donor not found!"
|
||||
}
|
||||
|
||||
/**
|
||||
* Error to throw when two donors' ids don't match.
|
||||
* Usually occurs when a user tries to change a donor's id.
|
||||
*/
|
||||
export class DonorIdsNotMatchingError extends NotAcceptableError {
|
||||
@IsString()
|
||||
name = "DonorIdsNotMatchingError"
|
||||
|
||||
@IsString()
|
||||
message = "The ids don't match! \n And if you wanted to change a donor's id: This isn't allowed!"
|
||||
}
|
||||
|
||||
/**
|
||||
* Error to throw when a donor needs a receipt, but no address is associated with them.
|
||||
*/
|
||||
export class DonorReceiptAddressNeededError extends NotAcceptableError {
|
||||
@IsString()
|
||||
name = "DonorReceiptAddressNeededError"
|
||||
|
||||
@IsString()
|
||||
message = "An address is needed to create a receipt for a donor. \n You didn't provide one."
|
||||
}
|
||||
25
src/errors/StatsClientErrors.ts
Normal file
25
src/errors/StatsClientErrors.ts
Normal file
@@ -0,0 +1,25 @@
|
||||
import { IsString } from 'class-validator';
|
||||
import { NotAcceptableError, NotFoundError } from 'routing-controllers';
|
||||
|
||||
/**
|
||||
* Error to throw, when a non-existant stats client get's loaded.
|
||||
*/
|
||||
export class StatsClientNotFoundError extends NotFoundError {
|
||||
@IsString()
|
||||
name = "StatsClientNotFoundError"
|
||||
|
||||
@IsString()
|
||||
message = "The stats client you provided couldn't be located in the system. \n Please check your request."
|
||||
}
|
||||
|
||||
/**
|
||||
* Error to throw when two stats clients' ids don't match.
|
||||
* Usually occurs when a user tries to change a stats client's id.
|
||||
*/
|
||||
export class StatsClientIdsNotMatchingError extends NotAcceptableError {
|
||||
@IsString()
|
||||
name = "StatsClientIdsNotMatchingError"
|
||||
|
||||
@IsString()
|
||||
message = "The ids don't match! \n And if you wanted to change a stats client's id: This isn't allowed!"
|
||||
}
|
||||
@@ -22,4 +22,15 @@ export class TrackIdsNotMatchingError extends NotAcceptableError {
|
||||
|
||||
@IsString()
|
||||
message = "The ids don't match! \n And if you wanted to change a track's id: This isn't allowed"
|
||||
}
|
||||
|
||||
/**
|
||||
* Error to throw when a track's lap time is set to a negative value.
|
||||
*/
|
||||
export class TrackLapTimeCantBeNegativeError extends NotAcceptableError {
|
||||
@IsString()
|
||||
name = "TrackLapTimeCantBeNegativeError"
|
||||
|
||||
@IsString()
|
||||
message = "The minimum lap time you provided is negative - That isn't possible. \n If you wanted to disable it: Just set it to 0/null."
|
||||
}
|
||||
@@ -35,13 +35,18 @@ export default async (app: Application) => {
|
||||
"in": "cookie",
|
||||
"name": "lfk_backend__refresh_token",
|
||||
description: "A cookie containing a JWT based refreh token. Attention: Doesn't work in swagger-ui. Use /api/auth/login or /api/auth/refresh to get one."
|
||||
},
|
||||
"StatsApiToken": {
|
||||
"type": "http",
|
||||
"scheme": "bearer",
|
||||
description: "Api token that can be obtained by creating a new stats client (post to /api/statsclients)."
|
||||
}
|
||||
}
|
||||
},
|
||||
info: {
|
||||
description: "The the backend API for the LfK! runner system.",
|
||||
title: "LfK! Backend API",
|
||||
version: "0.0.5",
|
||||
version: "0.0.8",
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
65
src/middlewares/StatsAuth.ts
Normal file
65
src/middlewares/StatsAuth.ts
Normal file
@@ -0,0 +1,65 @@
|
||||
import * as argon2 from "argon2";
|
||||
import { Request, Response } from 'express';
|
||||
import { getConnectionManager } from 'typeorm';
|
||||
import { StatsClient } from '../models/entities/StatsClient';
|
||||
import authchecker from './authchecker';
|
||||
|
||||
/**
|
||||
* This middleware handels the authentification of stats client api tokens.
|
||||
* The tokens have to be provided via Bearer auth header.
|
||||
* @param req Express request object.
|
||||
* @param res Express response object.
|
||||
* @param next Next function to call on success.
|
||||
*/
|
||||
const StatsAuth = async (req: Request, res: Response, next: () => void) => {
|
||||
let provided_token: string = req.headers["authorization"];
|
||||
if (provided_token == "" || provided_token === undefined || provided_token === null) {
|
||||
res.status(401).send("No api token provided.");
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
provided_token = provided_token.replace("Bearer ", "");
|
||||
} catch (error) {
|
||||
res.status(401).send("No valid jwt or api token provided.");
|
||||
return;
|
||||
}
|
||||
|
||||
let prefix = "";
|
||||
try {
|
||||
prefix = provided_token.split(".")[0];
|
||||
}
|
||||
finally {
|
||||
if (prefix == "" || prefix == undefined || prefix == null) {
|
||||
res.status(401).send("Api token non-existant or invalid syntax.");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
const client = await getConnectionManager().get().getRepository(StatsClient).findOne({ prefix: prefix });
|
||||
if (!client) {
|
||||
let user_authorized = false;
|
||||
try {
|
||||
let action = { request: req, response: res, context: null, next: next }
|
||||
user_authorized = await authchecker(action, ["RUNNER:GET", "TEAM:GET", "ORGANISATION:GET"]);
|
||||
}
|
||||
finally {
|
||||
if (user_authorized == false) {
|
||||
res.status(401).send("Api token non-existant or invalid syntax.");
|
||||
return;
|
||||
}
|
||||
else {
|
||||
next();
|
||||
}
|
||||
}
|
||||
}
|
||||
else {
|
||||
if (!(await argon2.verify(client.key, provided_token))) {
|
||||
res.status(401).send("Api token invalid.");
|
||||
return;
|
||||
}
|
||||
|
||||
next();
|
||||
}
|
||||
}
|
||||
export default StatsAuth;
|
||||
@@ -2,10 +2,10 @@ import cookie from "cookie";
|
||||
import * as jwt from "jsonwebtoken";
|
||||
import { Action } from "routing-controllers";
|
||||
import { getConnectionManager } from 'typeorm';
|
||||
import { config } from './config';
|
||||
import { IllegalJWTError, NoPermissionError, UserDisabledError, UserNonexistantOrRefreshtokenInvalidError } from './errors/AuthError';
|
||||
import { JwtCreator, JwtUser } from './jwtcreator';
|
||||
import { User } from './models/entities/User';
|
||||
import { config } from '../config';
|
||||
import { IllegalJWTError, NoPermissionError, UserDisabledError, UserNonexistantOrRefreshtokenInvalidError } from '../errors/AuthError';
|
||||
import { JwtCreator, JwtUser } from '../jwtcreator';
|
||||
import { User } from '../models/entities/User';
|
||||
|
||||
/**
|
||||
* Handels authorisation verification via jwt's for all api endpoints using the @Authorized decorator.
|
||||
38
src/models/actions/CreateDonor.ts
Normal file
38
src/models/actions/CreateDonor.ts
Normal file
@@ -0,0 +1,38 @@
|
||||
import { IsBoolean, IsOptional } from 'class-validator';
|
||||
import { DonorReceiptAddressNeededError } from '../../errors/DonorErrors';
|
||||
import { Donor } from '../entities/Donor';
|
||||
import { CreateParticipant } from './CreateParticipant';
|
||||
|
||||
/**
|
||||
* This classed is used to create a new Donor entity from a json body (post request).
|
||||
*/
|
||||
export class CreateDonor extends CreateParticipant {
|
||||
|
||||
/**
|
||||
* Does this donor need a receipt?
|
||||
*/
|
||||
@IsBoolean()
|
||||
@IsOptional()
|
||||
receiptNeeded?: boolean = false;
|
||||
|
||||
/**
|
||||
* Creates a new Donor entity from this.
|
||||
*/
|
||||
public async toDonor(): Promise<Donor> {
|
||||
let newDonor: Donor = new Donor();
|
||||
|
||||
newDonor.firstname = this.firstname;
|
||||
newDonor.middlename = this.middlename;
|
||||
newDonor.lastname = this.lastname;
|
||||
newDonor.phone = this.phone;
|
||||
newDonor.email = this.email;
|
||||
newDonor.address = await this.getAddress();
|
||||
newDonor.receiptNeeded = this.receiptNeeded;
|
||||
|
||||
if (this.receiptNeeded == true && this.address == null) {
|
||||
throw new DonorReceiptAddressNeededError()
|
||||
}
|
||||
|
||||
return newDonor;
|
||||
}
|
||||
}
|
||||
@@ -41,7 +41,7 @@ export class CreateRunnerOrganisation extends CreateRunnerGroup {
|
||||
|
||||
newRunnerOrganisation.name = this.name;
|
||||
newRunnerOrganisation.contact = await this.getContact();
|
||||
newRunnerOrganisation.address = await this.getAddress();
|
||||
// newRunnerOrganisation.address = await this.getAddress();
|
||||
|
||||
return newRunnerOrganisation;
|
||||
}
|
||||
|
||||
33
src/models/actions/CreateStatsClient.ts
Normal file
33
src/models/actions/CreateStatsClient.ts
Normal file
@@ -0,0 +1,33 @@
|
||||
import * as argon2 from "argon2";
|
||||
import { IsOptional, IsString } from 'class-validator';
|
||||
import crypto from 'crypto';
|
||||
import * as uuid from 'uuid';
|
||||
import { StatsClient } from '../entities/StatsClient';
|
||||
|
||||
/**
|
||||
* This classed is used to create a new StatsClient entity from a json body (post request).
|
||||
*/
|
||||
export class CreateStatsClient {
|
||||
/**
|
||||
* The new client's description.
|
||||
*/
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
description?: string;
|
||||
|
||||
/**
|
||||
* Converts this to a StatsClient entity.
|
||||
*/
|
||||
public async toStatsClient(): Promise<StatsClient> {
|
||||
let newClient: StatsClient = new StatsClient();
|
||||
|
||||
newClient.description = this.description;
|
||||
|
||||
let newUUID = uuid.v4().toUpperCase();
|
||||
newClient.prefix = crypto.createHash("sha3-512").update(newUUID).digest('hex').substring(0, 7).toUpperCase();
|
||||
newClient.key = await argon2.hash(newClient.prefix + "." + newUUID);
|
||||
newClient.cleartextkey = newClient.prefix + "." + newUUID;
|
||||
|
||||
return newClient;
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import { IsInt, IsNotEmpty, IsPositive, IsString } from 'class-validator';
|
||||
import { IsInt, IsNotEmpty, IsOptional, IsPositive, IsString } from 'class-validator';
|
||||
import { TrackLapTimeCantBeNegativeError } from '../../errors/TrackErrors';
|
||||
import { Track } from '../entities/Track';
|
||||
|
||||
/**
|
||||
@@ -19,6 +20,14 @@ export class CreateTrack {
|
||||
@IsPositive()
|
||||
distance: number;
|
||||
|
||||
/**
|
||||
* The minimum time a runner should take to run a lap on this track (in seconds).
|
||||
* Will be used for fraud detection.
|
||||
*/
|
||||
@IsInt()
|
||||
@IsOptional()
|
||||
minimumLapTime: number;
|
||||
|
||||
/**
|
||||
* Creates a new Track entity from this.
|
||||
*/
|
||||
@@ -27,6 +36,10 @@ export class CreateTrack {
|
||||
|
||||
newTrack.name = this.name;
|
||||
newTrack.distance = this.distance;
|
||||
newTrack.minimumLapTime = this.minimumLapTime;
|
||||
if (this.minimumLapTime < 0) {
|
||||
throw new TrackLapTimeCantBeNegativeError();
|
||||
}
|
||||
|
||||
return newTrack;
|
||||
}
|
||||
|
||||
44
src/models/actions/UpdateDonor.ts
Normal file
44
src/models/actions/UpdateDonor.ts
Normal file
@@ -0,0 +1,44 @@
|
||||
import { IsBoolean, IsInt, IsOptional } from 'class-validator';
|
||||
import { DonorReceiptAddressNeededError } from '../../errors/DonorErrors';
|
||||
import { Donor } from '../entities/Donor';
|
||||
import { CreateParticipant } from './CreateParticipant';
|
||||
|
||||
/**
|
||||
* This class is used to update a Donor entity (via put request).
|
||||
*/
|
||||
export class UpdateDonor extends CreateParticipant {
|
||||
|
||||
/**
|
||||
* The updated donor's id.
|
||||
* This shouldn't have changed but it is here in case anyone ever wants to enable id changes (whyever they would want to).
|
||||
*/
|
||||
@IsInt()
|
||||
id: number;
|
||||
|
||||
/**
|
||||
* Does the updated donor need a receipt?
|
||||
*/
|
||||
@IsBoolean()
|
||||
@IsOptional()
|
||||
receiptNeeded?: boolean;
|
||||
|
||||
|
||||
/**
|
||||
* Updates a provided Donor entity based on this.
|
||||
*/
|
||||
public async updateDonor(donor: Donor): Promise<Donor> {
|
||||
donor.firstname = this.firstname;
|
||||
donor.middlename = this.middlename;
|
||||
donor.lastname = this.lastname;
|
||||
donor.phone = this.phone;
|
||||
donor.email = this.email;
|
||||
donor.receiptNeeded = this.receiptNeeded;
|
||||
donor.address = await this.getAddress();
|
||||
|
||||
if (this.receiptNeeded == true && this.address == null) {
|
||||
throw new DonorReceiptAddressNeededError()
|
||||
}
|
||||
|
||||
return donor;
|
||||
}
|
||||
}
|
||||
@@ -45,7 +45,7 @@ export class UpdateRunnerOrganisation extends CreateRunnerGroup {
|
||||
|
||||
organisation.name = this.name;
|
||||
organisation.contact = await this.getContact();
|
||||
organisation.address = await this.getAddress();
|
||||
// organisation.address = await this.getAddress();
|
||||
|
||||
return organisation;
|
||||
}
|
||||
|
||||
50
src/models/actions/UpdateTrack.ts
Normal file
50
src/models/actions/UpdateTrack.ts
Normal file
@@ -0,0 +1,50 @@
|
||||
import { IsInt, IsNotEmpty, IsOptional, IsPositive, IsString } from 'class-validator';
|
||||
import { TrackLapTimeCantBeNegativeError } from '../../errors/TrackErrors';
|
||||
import { Track } from '../entities/Track';
|
||||
|
||||
/**
|
||||
* This class is used to update a Track entity (via put request).
|
||||
*/
|
||||
export class UpdateTrack {
|
||||
/**
|
||||
* The updated track's id.
|
||||
* This shouldn't have changed but it is here in case anyone ever wants to enable id changes (whyever they would want to).
|
||||
*/
|
||||
@IsInt()
|
||||
id: number;
|
||||
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
name: string;
|
||||
|
||||
/**
|
||||
* The updated track's distance in meters (must be greater than 0).
|
||||
*/
|
||||
@IsInt()
|
||||
@IsPositive()
|
||||
distance: number;
|
||||
|
||||
/**
|
||||
* The minimum time a runner should take to run a lap on this track (in seconds).
|
||||
* Will be used for fraud detection.
|
||||
*/
|
||||
@IsInt()
|
||||
@IsOptional()
|
||||
minimumLapTime: number;
|
||||
|
||||
|
||||
/**
|
||||
* Update a Track entity based on this.
|
||||
* @param track The track that shall be updated.
|
||||
*/
|
||||
public updateTrack(track: Track): Track {
|
||||
track.name = this.name;
|
||||
track.distance = this.distance;
|
||||
track.minimumLapTime = this.minimumLapTime;
|
||||
if (this.minimumLapTime < 0) {
|
||||
throw new TrackLapTimeCantBeNegativeError();
|
||||
}
|
||||
|
||||
return track;
|
||||
}
|
||||
}
|
||||
@@ -7,8 +7,7 @@ import {
|
||||
} from "class-validator";
|
||||
import { Column, Entity, OneToMany, PrimaryGeneratedColumn } from "typeorm";
|
||||
import { config } from '../../config';
|
||||
import { Participant } from "./Participant";
|
||||
import { RunnerOrganisation } from "./RunnerOrganisation";
|
||||
import { IAddressUser } from './IAddressUser';
|
||||
|
||||
/**
|
||||
* Defines the Address entity.
|
||||
@@ -79,12 +78,6 @@ export class Address {
|
||||
/**
|
||||
* Used to link the address to participants.
|
||||
*/
|
||||
@OneToMany(() => Participant, participant => participant.address, { nullable: true })
|
||||
participants: Participant[];
|
||||
|
||||
/**
|
||||
* Used to link the address to runner groups.
|
||||
*/
|
||||
@OneToMany(() => RunnerOrganisation, group => group.address, { nullable: true })
|
||||
groups: RunnerOrganisation[];
|
||||
@OneToMany(() => IAddressUser, addressUser => addressUser.address, { nullable: true })
|
||||
addressUsers: IAddressUser[];
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@ import {
|
||||
IsNotEmpty
|
||||
} from "class-validator";
|
||||
import { Entity, ManyToOne, PrimaryGeneratedColumn, TableInheritance } from "typeorm";
|
||||
import { Participant } from "./Participant";
|
||||
import { Donor } from './Donor';
|
||||
|
||||
/**
|
||||
* Defines the Donation entity.
|
||||
@@ -24,12 +24,12 @@ export abstract class Donation {
|
||||
* The donations's donor.
|
||||
*/
|
||||
@IsNotEmpty()
|
||||
@ManyToOne(() => Participant, donor => donor.donations)
|
||||
donor: Participant;
|
||||
@ManyToOne(() => Donor, donor => donor.donations)
|
||||
donor: Donor;
|
||||
|
||||
/**
|
||||
* The donation's amount in cents (or whatever your currency's smallest unit is.).
|
||||
* The exact implementation may differ for each type of donation.
|
||||
*/
|
||||
abstract amount: number | Promise<number>;
|
||||
abstract amount: number;
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
import { IsBoolean } from "class-validator";
|
||||
import { ChildEntity, Column } from "typeorm";
|
||||
import { ChildEntity, Column, OneToMany } from "typeorm";
|
||||
import { Donation } from './Donation';
|
||||
import { Participant } from "./Participant";
|
||||
|
||||
/**
|
||||
@@ -14,4 +15,11 @@ export class Donor extends Participant {
|
||||
@Column()
|
||||
@IsBoolean()
|
||||
receiptNeeded: boolean = false;
|
||||
|
||||
/**
|
||||
* Used to link the participant as the donor of a donation.
|
||||
* Attention: Only runner's can be associated as a distanceDonations distance source.
|
||||
*/
|
||||
@OneToMany(() => Donation, donation => donation.donor, { nullable: true })
|
||||
donations: Donation[];
|
||||
}
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
import { Column, Entity, ManyToOne, OneToMany, PrimaryGeneratedColumn } from "typeorm";
|
||||
import { config } from '../../config';
|
||||
import { Address } from "./Address";
|
||||
import { IAddressUser } from './IAddressUser';
|
||||
import { RunnerGroup } from "./RunnerGroup";
|
||||
|
||||
/**
|
||||
@@ -17,7 +18,7 @@ import { RunnerGroup } from "./RunnerGroup";
|
||||
* Mainly it's own class to reduce duplicate code and enable contact's to be associated with multiple groups.
|
||||
*/
|
||||
@Entity()
|
||||
export class GroupContact {
|
||||
export class GroupContact implements IAddressUser {
|
||||
/**
|
||||
* Autogenerated unique id (primary key).
|
||||
*/
|
||||
@@ -54,7 +55,7 @@ export class GroupContact {
|
||||
* This is a address object to prevent any formatting differences.
|
||||
*/
|
||||
@IsOptional()
|
||||
@ManyToOne(() => Address, address => address.participants, { nullable: true })
|
||||
@ManyToOne(() => Address, address => address.addressUsers, { nullable: true })
|
||||
address?: Address;
|
||||
|
||||
/**
|
||||
|
||||
15
src/models/entities/IAddressUser.ts
Normal file
15
src/models/entities/IAddressUser.ts
Normal file
@@ -0,0 +1,15 @@
|
||||
import { Entity, ManyToOne, PrimaryColumn } from 'typeorm';
|
||||
import { Address } from './Address';
|
||||
|
||||
/**
|
||||
* The interface(tm) all entities using addresses have to implement.
|
||||
* This is a abstract class, because apparently typeorm can't really work with interfaces :/
|
||||
*/
|
||||
@Entity()
|
||||
export abstract class IAddressUser {
|
||||
@PrimaryColumn()
|
||||
id: number;
|
||||
|
||||
@ManyToOne(() => Address, address => address.addressUsers, { nullable: true })
|
||||
address?: Address
|
||||
}
|
||||
@@ -7,10 +7,10 @@ import {
|
||||
|
||||
IsString
|
||||
} from "class-validator";
|
||||
import { Column, Entity, ManyToOne, OneToMany, PrimaryGeneratedColumn, TableInheritance } from "typeorm";
|
||||
import { Column, Entity, ManyToOne, PrimaryGeneratedColumn, TableInheritance } from "typeorm";
|
||||
import { config } from '../../config';
|
||||
import { Address } from "./Address";
|
||||
import { Donation } from "./Donation";
|
||||
import { IAddressUser } from './IAddressUser';
|
||||
|
||||
/**
|
||||
* Defines the Participant entity.
|
||||
@@ -18,7 +18,7 @@ import { Donation } from "./Donation";
|
||||
*/
|
||||
@Entity()
|
||||
@TableInheritance({ column: { name: "type", type: "varchar" } })
|
||||
export abstract class Participant {
|
||||
export abstract class Participant implements IAddressUser {
|
||||
/**
|
||||
* Autogenerated unique id (primary key).
|
||||
*/
|
||||
@@ -54,7 +54,7 @@ export abstract class Participant {
|
||||
* The participant's address.
|
||||
* This is a address object to prevent any formatting differences.
|
||||
*/
|
||||
@ManyToOne(() => Address, address => address.participants, { nullable: true })
|
||||
@ManyToOne(() => Address, address => address.addressUsers, { nullable: true })
|
||||
address?: Address;
|
||||
|
||||
/**
|
||||
@@ -74,11 +74,4 @@ export abstract class Participant {
|
||||
@IsOptional()
|
||||
@IsEmail()
|
||||
email?: string;
|
||||
|
||||
/**
|
||||
* Used to link the participant as the donor of a donation.
|
||||
* Attention: Only runner's can be associated as a distanceDonations distance source.
|
||||
*/
|
||||
@OneToMany(() => Donation, donation => donation.donor, { nullable: true })
|
||||
donations: Donation[];
|
||||
}
|
||||
@@ -18,7 +18,7 @@ export class Runner extends Participant {
|
||||
* Can be a runner team or organisation.
|
||||
*/
|
||||
@IsNotEmpty()
|
||||
@ManyToOne(() => RunnerGroup, group => group.runners, { nullable: false })
|
||||
@ManyToOne(() => RunnerGroup, group => group.runners)
|
||||
group: RunnerGroup;
|
||||
|
||||
/**
|
||||
@@ -58,4 +58,12 @@ export class Runner extends Participant {
|
||||
public get distance(): number {
|
||||
return this.validScans.reduce((sum, current) => sum + current.distance, 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the total donations a runner has collected based on his linked donations and distance ran.
|
||||
*/
|
||||
@IsInt()
|
||||
public get distanceDonationAmount(): number {
|
||||
return this.distanceDonations.reduce((sum, current) => sum + current.amountPerDistance, 0) * this.distance;
|
||||
}
|
||||
}
|
||||
@@ -44,4 +44,20 @@ export abstract class RunnerGroup {
|
||||
*/
|
||||
@OneToMany(() => Runner, runner => runner.group, { nullable: true })
|
||||
runners: Runner[];
|
||||
|
||||
/**
|
||||
* Returns the total distance ran by this group's runners based on all their valid scans.
|
||||
*/
|
||||
@IsInt()
|
||||
public get distance(): number {
|
||||
return this.runners.reduce((sum, current) => sum + current.distance, 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the total donations a runner has collected based on his linked donations and distance ran.
|
||||
*/
|
||||
@IsInt()
|
||||
public get distanceDonationAmount(): number {
|
||||
return this.runners.reduce((sum, current) => sum + current.distanceDonationAmount, 0);
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,8 @@
|
||||
import { IsOptional } from "class-validator";
|
||||
import { IsInt, IsOptional } from "class-validator";
|
||||
import { ChildEntity, ManyToOne, OneToMany } from "typeorm";
|
||||
import { Address } from "./Address";
|
||||
import { Address } from './Address';
|
||||
import { IAddressUser } from './IAddressUser';
|
||||
import { Runner } from './Runner';
|
||||
import { RunnerGroup } from "./RunnerGroup";
|
||||
import { RunnerTeam } from "./RunnerTeam";
|
||||
|
||||
@@ -9,13 +11,13 @@ import { RunnerTeam } from "./RunnerTeam";
|
||||
* This usually is a school, club or company.
|
||||
*/
|
||||
@ChildEntity()
|
||||
export class RunnerOrganisation extends RunnerGroup {
|
||||
export class RunnerOrganisation extends RunnerGroup implements IAddressUser {
|
||||
|
||||
/**
|
||||
* The organisations's address.
|
||||
*/
|
||||
@IsOptional()
|
||||
@ManyToOne(() => Address, address => address.groups, { nullable: true })
|
||||
@ManyToOne(() => Address, address => address.addressUsers, { nullable: true })
|
||||
address?: Address;
|
||||
|
||||
/**
|
||||
@@ -24,4 +26,32 @@ export class RunnerOrganisation extends RunnerGroup {
|
||||
*/
|
||||
@OneToMany(() => RunnerTeam, team => team.parentGroup, { nullable: true })
|
||||
teams: RunnerTeam[];
|
||||
|
||||
/**
|
||||
* Returns all runners associated with this organisation (directly or indirectly via teams).
|
||||
*/
|
||||
public get allRunners(): Runner[] {
|
||||
let returnRunners: Runner[] = new Array<Runner>();
|
||||
returnRunners.push(...this.runners);
|
||||
for (let team of this.teams) {
|
||||
returnRunners.push(...team.runners)
|
||||
}
|
||||
return returnRunners;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the total distance ran by this group's runners based on all their valid scans.
|
||||
*/
|
||||
@IsInt()
|
||||
public get distance(): number {
|
||||
return this.allRunners.reduce((sum, current) => sum + current.distance, 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the total donations a runner has collected based on his linked donations and distance ran.
|
||||
*/
|
||||
@IsInt()
|
||||
public get distanceDonationAmount(): number {
|
||||
return this.allRunners.reduce((sum, current) => sum + current.distanceDonationAmount, 0);
|
||||
}
|
||||
}
|
||||
48
src/models/entities/StatsClient.ts
Normal file
48
src/models/entities/StatsClient.ts
Normal file
@@ -0,0 +1,48 @@
|
||||
import { IsInt, IsOptional, IsString } from "class-validator";
|
||||
import { Column, Entity, PrimaryGeneratedColumn } from "typeorm";
|
||||
/**
|
||||
* Defines the StatsClient entity.
|
||||
* StatsClients can be used to access the protected parts of the stats api (top runners, donators and so on).
|
||||
*/
|
||||
@Entity()
|
||||
export class StatsClient {
|
||||
/**
|
||||
* Autogenerated unique id (primary key).
|
||||
*/
|
||||
@PrimaryGeneratedColumn()
|
||||
@IsInt()
|
||||
id: number;
|
||||
|
||||
/**
|
||||
* The clients's description.
|
||||
* Mostly for better UX when traceing back stuff.
|
||||
*/
|
||||
@Column({ nullable: true })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
description?: string;
|
||||
|
||||
/**
|
||||
* The client's api key prefix.
|
||||
* This is used identitfy a client by it's api key.
|
||||
*/
|
||||
@Column({ unique: true })
|
||||
@IsString()
|
||||
prefix: string;
|
||||
|
||||
/**
|
||||
* The client's api key hash.
|
||||
* The api key can be used to authenticate against the /stats/** routes.
|
||||
*/
|
||||
@Column()
|
||||
@IsString()
|
||||
key: string;
|
||||
|
||||
/**
|
||||
* The client's api key in plain text.
|
||||
* This will only be used to display the full key on creation and updates.
|
||||
*/
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
cleartextkey?: string;
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import {
|
||||
IsInt,
|
||||
IsNotEmpty,
|
||||
IsOptional,
|
||||
IsPositive,
|
||||
IsString
|
||||
} from "class-validator";
|
||||
@@ -18,7 +19,7 @@ export class Track {
|
||||
*/
|
||||
@PrimaryGeneratedColumn()
|
||||
@IsInt()
|
||||
id: number;;
|
||||
id: number;
|
||||
|
||||
/**
|
||||
* The track's name.
|
||||
@@ -38,6 +39,15 @@ export class Track {
|
||||
@IsPositive()
|
||||
distance: number;
|
||||
|
||||
/**
|
||||
* The minimum time a runner should take to run a lap on this track (in seconds).
|
||||
* Will be used for fraud detection.
|
||||
*/
|
||||
@Column({ nullable: true })
|
||||
@IsInt()
|
||||
@IsOptional()
|
||||
minimumLapTime?: number;
|
||||
|
||||
/**
|
||||
* Used to link scan stations to a certain track.
|
||||
* This makes the configuration of the scan stations easier.
|
||||
|
||||
@@ -8,5 +8,7 @@ export enum PermissionTarget {
|
||||
TRACK = 'TRACK',
|
||||
USER = 'USER',
|
||||
USERGROUP = 'USERGROUP',
|
||||
PERMISSION = 'PERMISSION'
|
||||
PERMISSION = 'PERMISSION',
|
||||
STATSCLIENT = 'STATSCLIENT',
|
||||
DONOR = 'DONOR'
|
||||
}
|
||||
26
src/models/responses/ResponseDonor.ts
Normal file
26
src/models/responses/ResponseDonor.ts
Normal file
@@ -0,0 +1,26 @@
|
||||
import {
|
||||
IsBoolean
|
||||
} from "class-validator";
|
||||
import { Donor } from '../entities/Donor';
|
||||
import { ResponseParticipant } from './ResponseParticipant';
|
||||
|
||||
/**
|
||||
* Defines the donor response.
|
||||
*/
|
||||
export class ResponseDonor extends ResponseParticipant {
|
||||
|
||||
/**
|
||||
* Does this donor need a receipt?
|
||||
*/
|
||||
@IsBoolean()
|
||||
receiptNeeded: boolean;
|
||||
|
||||
/**
|
||||
* Creates a ResponseRunner object from a runner.
|
||||
* @param runner The user the response shall be build for.
|
||||
*/
|
||||
public constructor(donor: Donor) {
|
||||
super(donor);
|
||||
this.receiptNeeded = donor.receiptNeeded;
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,8 @@
|
||||
import {
|
||||
IsArray,
|
||||
IsNotEmpty,
|
||||
IsObject
|
||||
|
||||
IsObject,
|
||||
IsOptional
|
||||
} from "class-validator";
|
||||
import { Address } from '../entities/Address';
|
||||
import { RunnerOrganisation } from '../entities/RunnerOrganisation';
|
||||
@@ -17,7 +18,7 @@ export class ResponseRunnerOrganisation extends ResponseRunnerGroup {
|
||||
* The runnerOrganisation's address.
|
||||
*/
|
||||
@IsObject()
|
||||
@IsNotEmpty()
|
||||
@IsOptional()
|
||||
address?: Address;
|
||||
|
||||
/**
|
||||
|
||||
83
src/models/responses/ResponseStats.ts
Normal file
83
src/models/responses/ResponseStats.ts
Normal file
@@ -0,0 +1,83 @@
|
||||
import {
|
||||
IsInt
|
||||
} from "class-validator";
|
||||
import { Donation } from '../entities/Donation';
|
||||
import { Runner } from '../entities/Runner';
|
||||
import { RunnerOrganisation } from '../entities/RunnerOrganisation';
|
||||
import { RunnerTeam } from '../entities/RunnerTeam';
|
||||
import { Scan } from '../entities/Scan';
|
||||
import { User } from '../entities/User';
|
||||
|
||||
/**
|
||||
* Defines the stats response.
|
||||
* The stats response calculates some basic stats for a dashboard or public display.
|
||||
*/
|
||||
export class ResponseStats {
|
||||
/**
|
||||
* The amount of runners registered in the system.
|
||||
*/
|
||||
@IsInt()
|
||||
total_runners: number;
|
||||
|
||||
/**
|
||||
* The amount of teams registered in the system.
|
||||
*/
|
||||
@IsInt()
|
||||
total_teams: number;
|
||||
|
||||
/**
|
||||
* The amount of organisations registered in the system.
|
||||
*/
|
||||
@IsInt()
|
||||
total_orgs: number;
|
||||
|
||||
/**
|
||||
* The amount of users registered in the system.
|
||||
*/
|
||||
@IsInt()
|
||||
total_users: number;
|
||||
|
||||
/**
|
||||
* The amount of valid scans registered in the system.
|
||||
*/
|
||||
@IsInt()
|
||||
total_scans: number;
|
||||
|
||||
/**
|
||||
* The total distance that all runners ran combined.
|
||||
*/
|
||||
@IsInt()
|
||||
total_distance: number;
|
||||
|
||||
/**
|
||||
* The total donation amount.
|
||||
*/
|
||||
@IsInt()
|
||||
total_donation: number;
|
||||
|
||||
/**
|
||||
* The average distance ran per runner.
|
||||
*/
|
||||
@IsInt()
|
||||
average_distance: number;
|
||||
|
||||
/**
|
||||
* Creates a new stats response containing some basic statistics for a dashboard or public display.
|
||||
* @param runners Array containing all runners - the following relations have to be resolved: scans, scans.track
|
||||
* @param teams Array containing all teams - no relations have to be resolved.
|
||||
* @param orgs Array containing all orgs - no relations have to be resolved.
|
||||
* @param users Array containing all users - no relations have to be resolved.
|
||||
* @param scans Array containing all scans - no relations have to be resolved.
|
||||
* @param donations Array containing all donations - the following relations have to be resolved: runner, runner.scans, runner.scans.track
|
||||
*/
|
||||
public constructor(runners: Runner[], teams: RunnerTeam[], orgs: RunnerOrganisation[], users: User[], scans: Scan[], donations: Donation[]) {
|
||||
this.total_runners = runners.length;
|
||||
this.total_teams = teams.length;
|
||||
this.total_orgs = orgs.length;
|
||||
this.total_users = users.length;
|
||||
this.total_scans = scans.filter(scan => { scan.valid === true }).length;
|
||||
this.total_distance = runners.reduce((sum, current) => sum + current.distance, 0);
|
||||
this.total_donation = donations.reduce((sum, current) => sum + current.amount, 0);
|
||||
this.average_distance = this.total_distance / this.total_runners;
|
||||
}
|
||||
}
|
||||
54
src/models/responses/ResponseStatsClient.ts
Normal file
54
src/models/responses/ResponseStatsClient.ts
Normal file
@@ -0,0 +1,54 @@
|
||||
import {
|
||||
|
||||
IsInt,
|
||||
|
||||
IsNotEmpty,
|
||||
|
||||
IsOptional,
|
||||
IsString
|
||||
} from "class-validator";
|
||||
import { StatsClient } from '../entities/StatsClient';
|
||||
|
||||
/**
|
||||
* Defines the statsClient response.
|
||||
*/
|
||||
export class ResponseStatsClient {
|
||||
/**
|
||||
* The client's id.
|
||||
*/
|
||||
@IsInt()
|
||||
id: number;
|
||||
|
||||
/**
|
||||
* The client's description.
|
||||
*/
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
description?: string;
|
||||
|
||||
/**
|
||||
* The client's api key.
|
||||
* Only visible on creation or regeneration.
|
||||
*/
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
key: string;
|
||||
|
||||
/**
|
||||
* The client's api key prefix.
|
||||
*/
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
prefix: string;
|
||||
|
||||
/**
|
||||
* Creates a ResponseStatsClient object from a statsClient.
|
||||
* @param client The statsClient the response shall be build for.
|
||||
*/
|
||||
public constructor(client: StatsClient) {
|
||||
this.id = client.id;
|
||||
this.description = client.description;
|
||||
this.prefix = client.prefix;
|
||||
this.key = "Only visible on creation.";
|
||||
}
|
||||
}
|
||||
47
src/models/responses/ResponseStatsOrganisation.ts
Normal file
47
src/models/responses/ResponseStatsOrganisation.ts
Normal file
@@ -0,0 +1,47 @@
|
||||
import {
|
||||
IsInt,
|
||||
|
||||
IsString
|
||||
} from "class-validator";
|
||||
import { RunnerOrganisation } from '../entities/RunnerOrganisation';
|
||||
|
||||
/**
|
||||
* Defines the org stats response.
|
||||
* This differs from the normal org responce.
|
||||
*/
|
||||
export class ResponseStatsOrgnisation {
|
||||
/**
|
||||
* The orgs's id.
|
||||
*/
|
||||
@IsInt()
|
||||
id: number;
|
||||
|
||||
/**
|
||||
* The orgs's name.
|
||||
*/
|
||||
@IsString()
|
||||
name: string;
|
||||
|
||||
/**
|
||||
* The orgs's runner's currently ran distance in meters.
|
||||
*/
|
||||
@IsInt()
|
||||
distance: number;
|
||||
|
||||
/**
|
||||
* The orgs's currently collected donations.
|
||||
*/
|
||||
@IsInt()
|
||||
donationAmount: number;
|
||||
|
||||
/**
|
||||
* Creates a new organisation stats response from a organisation
|
||||
* @param org The organisation whoes response shall be generated - the following relations have to be resolved: runners, runners.scans, runners.distanceDonations, runners.scans.track, teams, teams.runners, teams.runners.scans, teams.runners.distanceDonations, teams.runners.scans.track
|
||||
*/
|
||||
public constructor(org: RunnerOrganisation) {
|
||||
this.name = org.name;
|
||||
this.id = org.id;
|
||||
this.distance = org.distance;
|
||||
this.donationAmount = org.distanceDonationAmount;
|
||||
}
|
||||
}
|
||||
69
src/models/responses/ResponseStatsRunner.ts
Normal file
69
src/models/responses/ResponseStatsRunner.ts
Normal file
@@ -0,0 +1,69 @@
|
||||
import {
|
||||
IsInt,
|
||||
IsObject,
|
||||
IsString
|
||||
} from "class-validator";
|
||||
import { Runner } from '../entities/Runner';
|
||||
import { RunnerGroup } from '../entities/RunnerGroup';
|
||||
|
||||
/**
|
||||
* Defines the runner stats response.
|
||||
* This differs from the normal runner responce.
|
||||
*/
|
||||
export class ResponseStatsRunner {
|
||||
/**
|
||||
* The runner's id.
|
||||
*/
|
||||
@IsInt()
|
||||
id: number;
|
||||
|
||||
/**
|
||||
* The runner's first name.
|
||||
*/
|
||||
@IsString()
|
||||
firstname: string;
|
||||
|
||||
/**
|
||||
* The runner's middle name.
|
||||
*/
|
||||
@IsString()
|
||||
middlename?: string;
|
||||
|
||||
/**
|
||||
* The runner's last name.
|
||||
*/
|
||||
@IsString()
|
||||
lastname: string;
|
||||
|
||||
/**
|
||||
* The runner's currently ran distance in meters.
|
||||
*/
|
||||
@IsInt()
|
||||
distance: number;
|
||||
|
||||
/**
|
||||
* The runner's currently collected donations.
|
||||
*/
|
||||
@IsInt()
|
||||
donationAmount: number;
|
||||
|
||||
/**
|
||||
* The runner's group.
|
||||
*/
|
||||
@IsObject()
|
||||
group: RunnerGroup;
|
||||
|
||||
/**
|
||||
* Creates a new runner stats response from a runner
|
||||
* @param runner The runner whoes response shall be generated - the following relations have to be resolved: scans, group, distanceDonations, scans.track
|
||||
*/
|
||||
public constructor(runner: Runner) {
|
||||
this.id = runner.id;
|
||||
this.firstname = runner.firstname;
|
||||
this.middlename = runner.middlename;
|
||||
this.lastname = runner.lastname;
|
||||
this.distance = runner.distance;
|
||||
this.donationAmount = runner.distanceDonationAmount;
|
||||
this.group = runner.group;
|
||||
}
|
||||
}
|
||||
55
src/models/responses/ResponseStatsTeam.ts
Normal file
55
src/models/responses/ResponseStatsTeam.ts
Normal file
@@ -0,0 +1,55 @@
|
||||
import {
|
||||
IsInt,
|
||||
IsObject,
|
||||
IsString
|
||||
} from "class-validator";
|
||||
import { RunnerGroup } from '../entities/RunnerGroup';
|
||||
import { RunnerTeam } from '../entities/RunnerTeam';
|
||||
|
||||
/**
|
||||
* Defines the team stats response.
|
||||
* This differs from the normal team responce.
|
||||
*/
|
||||
export class ResponseStatsTeam {
|
||||
/**
|
||||
* The team's id.
|
||||
*/
|
||||
@IsInt()
|
||||
id: number;
|
||||
|
||||
/**
|
||||
* The team's name.
|
||||
*/
|
||||
@IsString()
|
||||
name: string;
|
||||
|
||||
/**
|
||||
* The teams's currently ran distance in meters.
|
||||
*/
|
||||
@IsInt()
|
||||
distance: number;
|
||||
|
||||
/**
|
||||
* The teams's currently collected donations.
|
||||
*/
|
||||
@IsInt()
|
||||
donationAmount: number;
|
||||
|
||||
/**
|
||||
* The teams's parent group.
|
||||
*/
|
||||
@IsObject()
|
||||
parent: RunnerGroup;
|
||||
|
||||
/**
|
||||
* Creates a new team stats response from a team
|
||||
* @param team The team whoes response shall be generated - the following relations have to be resolved: runners, runners.scans, runners.distanceDonations, runners.scans.track
|
||||
*/
|
||||
public constructor(team: RunnerTeam) {
|
||||
this.name = team.name;
|
||||
this.id = team.id;
|
||||
this.parent = team.parentGroup;
|
||||
this.distance = team.distance;
|
||||
this.donationAmount = team.distanceDonationAmount;
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import { IsInt, IsString } from "class-validator";
|
||||
import { IsInt, IsOptional, IsString } from "class-validator";
|
||||
import { TrackLapTimeCantBeNegativeError } from '../../errors/TrackErrors';
|
||||
import { Track } from '../entities/Track';
|
||||
|
||||
/**
|
||||
@@ -23,6 +24,14 @@ export class ResponseTrack {
|
||||
@IsInt()
|
||||
distance: number;
|
||||
|
||||
/**
|
||||
* The minimum time a runner should take to run a lap on this track (in seconds).
|
||||
* Will be used for fraud detection.
|
||||
*/
|
||||
@IsInt()
|
||||
@IsOptional()
|
||||
minimumLapTime?: number;
|
||||
|
||||
/**
|
||||
* Creates a ResponseTrack object from a track.
|
||||
* @param track The track the response shall be build for.
|
||||
@@ -31,5 +40,9 @@ export class ResponseTrack {
|
||||
this.id = track.id;
|
||||
this.name = track.name;
|
||||
this.distance = track.distance;
|
||||
this.minimumLapTime = track.minimumLapTime;
|
||||
if (this.minimumLapTime < 0) {
|
||||
throw new TrackLapTimeCantBeNegativeError();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
94
src/tests/donors/donor_add.spec.ts
Normal file
94
src/tests/donors/donor_add.spec.ts
Normal file
@@ -0,0 +1,94 @@
|
||||
import axios from 'axios';
|
||||
import { config } from '../../config';
|
||||
const base = "http://localhost:" + config.internal_port
|
||||
|
||||
let access_token;
|
||||
let axios_config;
|
||||
|
||||
beforeAll(async () => {
|
||||
const res = await axios.post(base + '/api/auth/login', { username: "demo", password: "demo" });
|
||||
access_token = res.data["access_token"];
|
||||
axios_config = {
|
||||
headers: { "authorization": "Bearer " + access_token },
|
||||
validateStatus: undefined
|
||||
};
|
||||
});
|
||||
|
||||
// ---------------
|
||||
describe('POST /api/donors with errors', () => {
|
||||
it('creating a new donor without any parameters should return 400', async () => {
|
||||
const res1 = await axios.post(base + '/api/donors', null, axios_config);
|
||||
expect(res1.status).toEqual(400);
|
||||
expect(res1.headers['content-type']).toContain("application/json")
|
||||
});
|
||||
it('creating a new donor without a last name should return 400', async () => {
|
||||
const res2 = await axios.post(base + '/api/donors', {
|
||||
"firstname": "first",
|
||||
"middlename": "middle"
|
||||
}, axios_config);
|
||||
expect(res2.status).toEqual(400);
|
||||
expect(res2.headers['content-type']).toContain("application/json")
|
||||
});
|
||||
it('creating a new donor with a invalid address should return 404', async () => {
|
||||
const res2 = await axios.post(base + '/api/donors', {
|
||||
"firstname": "first",
|
||||
"middlename": "middle",
|
||||
"lastname": "last",
|
||||
"address": 0
|
||||
}, axios_config);
|
||||
expect(res2.status).toEqual(404);
|
||||
expect(res2.headers['content-type']).toContain("application/json")
|
||||
});
|
||||
it('creating a new donor with a invalid phone number should return 400', async () => {
|
||||
const res2 = await axios.post(base + '/api/donors', {
|
||||
"firstname": "first",
|
||||
"middlename": "middle",
|
||||
"lastname": "last",
|
||||
"phone": "123"
|
||||
}, axios_config);
|
||||
expect(res2.status).toEqual(400);
|
||||
expect(res2.headers['content-type']).toContain("application/json")
|
||||
});
|
||||
it('creating a new donor with a invalid mail address should return 400', async () => {
|
||||
const res2 = await axios.post(base + '/api/donors', {
|
||||
"firstname": "string",
|
||||
"middlename": "string",
|
||||
"lastname": "string",
|
||||
"phone": null,
|
||||
"email": "123",
|
||||
}, axios_config);
|
||||
expect(res2.status).toEqual(400);
|
||||
expect(res2.headers['content-type']).toContain("application/json")
|
||||
});
|
||||
it('creating a new donor without an address but with receiptNeeded=true 406', async () => {
|
||||
const res2 = await axios.post(base + '/api/donors', {
|
||||
"firstname": "string",
|
||||
"middlename": "string",
|
||||
"lastname": "string",
|
||||
"receiptNeeded": true
|
||||
}, axios_config);
|
||||
expect(res2.status).toEqual(406);
|
||||
expect(res2.headers['content-type']).toContain("application/json")
|
||||
});
|
||||
});
|
||||
// ---------------
|
||||
describe('POST /api/donors working', () => {
|
||||
it('creating a new donor with only needed params should return 200', async () => {
|
||||
const res2 = await axios.post(base + '/api/donors', {
|
||||
"firstname": "first",
|
||||
"lastname": "last"
|
||||
}, axios_config);
|
||||
expect(res2.status).toEqual(200);
|
||||
expect(res2.headers['content-type']).toContain("application/json")
|
||||
});
|
||||
it('creating a new donor with all non-relationship optional params should return 200', async () => {
|
||||
const res3 = await axios.post(base + '/api/donors', {
|
||||
"firstname": "first",
|
||||
"middlename": "middle",
|
||||
"lastname": "last",
|
||||
"receiptNeeded": false
|
||||
}, axios_config);
|
||||
expect(res3.status).toEqual(200);
|
||||
expect(res3.headers['content-type']).toContain("application/json")
|
||||
});
|
||||
});
|
||||
47
src/tests/donors/donor_delete.spec.ts
Normal file
47
src/tests/donors/donor_delete.spec.ts
Normal file
@@ -0,0 +1,47 @@
|
||||
import axios from 'axios';
|
||||
import { config } from '../../config';
|
||||
const base = "http://localhost:" + config.internal_port
|
||||
|
||||
let access_token;
|
||||
let axios_config;
|
||||
|
||||
beforeAll(async () => {
|
||||
const res = await axios.post(base + '/api/auth/login', { username: "demo", password: "demo" });
|
||||
access_token = res.data["access_token"];
|
||||
axios_config = {
|
||||
headers: { "authorization": "Bearer " + access_token },
|
||||
validateStatus: undefined
|
||||
};
|
||||
});
|
||||
|
||||
describe('adding + deletion (non-existant)', () => {
|
||||
it('delete', async () => {
|
||||
const res2 = await axios.delete(base + '/api/donors/0', axios_config);
|
||||
expect(res2.status).toEqual(204);
|
||||
});
|
||||
});
|
||||
// ---------------
|
||||
describe('add+delete', () => {
|
||||
let added_donor;
|
||||
it('creating a new donor with only needed params should return 200', async () => {
|
||||
const res2 = await axios.post(base + '/api/donors', {
|
||||
"firstname": "first",
|
||||
"lastname": "last"
|
||||
}, axios_config);
|
||||
added_donor = res2.data;
|
||||
expect(res2.status).toEqual(200);
|
||||
expect(res2.headers['content-type']).toContain("application/json")
|
||||
});
|
||||
it('delete donor', async () => {
|
||||
const res3 = await axios.delete(base + '/api/donors/' + added_donor.id, axios_config);
|
||||
expect(res3.status).toEqual(200);
|
||||
expect(res3.headers['content-type']).toContain("application/json")
|
||||
let deleted_runner = res3.data
|
||||
expect(deleted_runner).toEqual(added_donor);
|
||||
});
|
||||
it('check if donor really was deleted', async () => {
|
||||
const res4 = await axios.get(base + '/api/donors/' + added_donor.id, axios_config);
|
||||
expect(res4.status).toEqual(404);
|
||||
expect(res4.headers['content-type']).toContain("application/json")
|
||||
});
|
||||
});
|
||||
57
src/tests/donors/donor_get.spec.ts
Normal file
57
src/tests/donors/donor_get.spec.ts
Normal file
@@ -0,0 +1,57 @@
|
||||
import axios from 'axios';
|
||||
import { config } from '../../config';
|
||||
const base = "http://localhost:" + config.internal_port
|
||||
let access_token;
|
||||
let axios_config;
|
||||
|
||||
beforeAll(async () => {
|
||||
const res = await axios.post(base + '/api/auth/login', { username: "demo", password: "demo" });
|
||||
access_token = res.data["access_token"];
|
||||
axios_config = {
|
||||
headers: { "authorization": "Bearer " + access_token },
|
||||
validateStatus: undefined
|
||||
};
|
||||
});
|
||||
|
||||
describe('GET /api/donors', () => {
|
||||
it('basic get should return 200', async () => {
|
||||
const res = await axios.get(base + '/api/donors', axios_config);
|
||||
expect(res.status).toEqual(200);
|
||||
expect(res.headers['content-type']).toContain("application/json")
|
||||
});
|
||||
});
|
||||
// ---------------
|
||||
describe('GET /api/donors/0', () => {
|
||||
it('basic get should return 404', async () => {
|
||||
const res = await axios.get(base + '/api/donors/0', axios_config);
|
||||
expect(res.status).toEqual(404);
|
||||
expect(res.headers['content-type']).toContain("application/json")
|
||||
});
|
||||
});
|
||||
// ---------------
|
||||
describe('GET /api/donors after adding', () => {
|
||||
let added_donor;
|
||||
it('creating a new donor with only needed params should return 200', async () => {
|
||||
const res2 = await axios.post(base + '/api/donors', {
|
||||
"firstname": "first",
|
||||
"lastname": "last"
|
||||
}, axios_config);
|
||||
added_donor = res2.data;
|
||||
expect(res2.status).toEqual(200);
|
||||
expect(res2.headers['content-type']).toContain("application/json")
|
||||
});
|
||||
it('explicit get should return 200', async () => {
|
||||
const res3 = await axios.get(base + '/api/donors/' + added_donor.id, axios_config);
|
||||
expect(res3.status).toEqual(200);
|
||||
expect(res3.headers['content-type']).toContain("application/json")
|
||||
let gotten_donor = res3.data
|
||||
expect(gotten_donor).toEqual(added_donor);
|
||||
});
|
||||
it('get from all runners should return 200', async () => {
|
||||
const res4 = await axios.get(base + '/api/donors/', axios_config);
|
||||
expect(res4.status).toEqual(200);
|
||||
expect(res4.headers['content-type']).toContain("application/json")
|
||||
let gotten_donors = res4.data
|
||||
expect(gotten_donors).toContainEqual(added_donor);
|
||||
});
|
||||
});
|
||||
75
src/tests/donors/donor_update.spec.ts
Normal file
75
src/tests/donors/donor_update.spec.ts
Normal file
@@ -0,0 +1,75 @@
|
||||
import axios from 'axios';
|
||||
import { config } from '../../config';
|
||||
const base = "http://localhost:" + config.internal_port
|
||||
|
||||
let access_token;
|
||||
let axios_config;
|
||||
|
||||
beforeAll(async () => {
|
||||
const res = await axios.post(base + '/api/auth/login', { username: "demo", password: "demo" });
|
||||
access_token = res.data["access_token"];
|
||||
axios_config = {
|
||||
headers: { "authorization": "Bearer " + access_token },
|
||||
validateStatus: undefined
|
||||
};
|
||||
});
|
||||
|
||||
describe('Update donor name after adding', () => {
|
||||
let added_donor;
|
||||
it('creating a new runner with only needed params should return 200', async () => {
|
||||
const res2 = await axios.post(base + '/api/donors', {
|
||||
"firstname": "first",
|
||||
"lastname": "last"
|
||||
}, axios_config);
|
||||
added_donor = res2.data;
|
||||
expect(res2.status).toEqual(200);
|
||||
expect(res2.headers['content-type']).toContain("application/json")
|
||||
});
|
||||
it('valid update should return 200', async () => {
|
||||
let donor_copy = added_donor
|
||||
donor_copy.firstname = "second"
|
||||
const res3 = await axios.put(base + '/api/donors/' + added_donor.id, donor_copy, axios_config);
|
||||
expect(res3.status).toEqual(200);
|
||||
expect(res3.headers['content-type']).toContain("application/json")
|
||||
let updated_donor = res3.data
|
||||
expect(updated_donor).toEqual(donor_copy);
|
||||
});
|
||||
});
|
||||
// ---------------
|
||||
describe('Update donor id after adding(should fail)', () => {
|
||||
let added_donor;
|
||||
it('creating a new donor with only needed params should return 200', async () => {
|
||||
const res2 = await axios.post(base + '/api/donors', {
|
||||
"firstname": "first",
|
||||
"lastname": "last"
|
||||
}, axios_config);
|
||||
added_donor = res2.data;
|
||||
expect(res2.status).toEqual(200);
|
||||
expect(res2.headers['content-type']).toContain("application/json")
|
||||
});
|
||||
it('invalid update should return 406', async () => {
|
||||
added_donor.id++;
|
||||
const res3 = await axios.put(base + '/api/donors/' + (added_donor.id - 1), added_donor, axios_config);
|
||||
expect(res3.status).toEqual(406);
|
||||
expect(res3.headers['content-type']).toContain("application/json")
|
||||
});
|
||||
});
|
||||
// ---------------
|
||||
describe('Update donor without address but receiptNeeded=true should fail', () => {
|
||||
let added_donor;
|
||||
it('creating a new donor with only needed params should return 200', async () => {
|
||||
const res2 = await axios.post(base + '/api/donors', {
|
||||
"firstname": "first",
|
||||
"lastname": "last",
|
||||
}, axios_config);
|
||||
added_donor = res2.data;
|
||||
expect(res2.status).toEqual(200);
|
||||
expect(res2.headers['content-type']).toContain("application/json")
|
||||
});
|
||||
it('invalid update should return 406', async () => {
|
||||
added_donor.receiptNeeded = true;
|
||||
const res3 = await axios.put(base + '/api/donors/' + added_donor.id, added_donor, axios_config);
|
||||
expect(res3.status).toEqual(406);
|
||||
expect(res3.headers['content-type']).toContain("application/json")
|
||||
});
|
||||
});
|
||||
@@ -1,116 +0,0 @@
|
||||
import axios from 'axios';
|
||||
import { config } from '../config';
|
||||
const base = "http://localhost:" + config.internal_port
|
||||
|
||||
let access_token;
|
||||
let axios_config;
|
||||
|
||||
beforeAll(async () => {
|
||||
const res = await axios.post(base + '/api/auth/login', { username: "demo", password: "demo" });
|
||||
access_token = res.data["access_token"];
|
||||
axios_config = {
|
||||
headers: { "authorization": "Bearer " + access_token },
|
||||
validateStatus: undefined
|
||||
};
|
||||
});
|
||||
|
||||
describe('GET /api/tracks', () => {
|
||||
it('basic get should return 200', async () => {
|
||||
const res = await axios.get(base + '/api/tracks', axios_config);
|
||||
expect(res.status).toEqual(200);
|
||||
expect(res.headers['content-type']).toContain("application/json")
|
||||
});
|
||||
it('correct distance input should return 200', async () => {
|
||||
const res = await axios.post(base + '/api/tracks', {
|
||||
"name": "string",
|
||||
"distance": 400
|
||||
}, axios_config);
|
||||
expect(res.status).toEqual(200);
|
||||
expect(res.headers['content-type']).toContain("application/json")
|
||||
});
|
||||
});
|
||||
// ---------------
|
||||
describe('POST /api/tracks', () => {
|
||||
it('illegal distance input should return 400', async () => {
|
||||
const res = await axios.post(base + '/api/tracks', {
|
||||
"name": "string",
|
||||
"distance": -1
|
||||
}, axios_config);
|
||||
expect(res.status).toEqual(400);
|
||||
expect(res.headers['content-type']).toContain("application/json")
|
||||
});
|
||||
it('correct distance input should return 200', async () => {
|
||||
const res = await axios.post(base + '/api/tracks', {
|
||||
"name": "string",
|
||||
"distance": 400
|
||||
}, axios_config);
|
||||
expect(res.status).toEqual(200);
|
||||
expect(res.headers['content-type']).toContain("application/json")
|
||||
});
|
||||
});
|
||||
// ---------------
|
||||
describe('adding + getting tracks', () => {
|
||||
it('correct distance input should return 200', async () => {
|
||||
const res = await axios.post(base + '/api/tracks', {
|
||||
"name": "string",
|
||||
"distance": 1000
|
||||
}, axios_config);
|
||||
expect(res.status).toEqual(200);
|
||||
expect(res.headers['content-type']).toContain("application/json")
|
||||
});
|
||||
it('check if track was added', async () => {
|
||||
const res = await axios.get(base + '/api/tracks', axios_config);
|
||||
expect(res.status).toEqual(200);
|
||||
expect(res.headers['content-type']).toContain("application/json")
|
||||
let added_track = res.data[res.data.length - 1]
|
||||
delete added_track.id
|
||||
expect(added_track).toEqual({
|
||||
"name": "string",
|
||||
"distance": 1000
|
||||
})
|
||||
});
|
||||
});
|
||||
// ---------------
|
||||
describe('adding + getting + updating', () => {
|
||||
let added_track_id
|
||||
it('correct distance input should return 200', async () => {
|
||||
const res = await axios.post(base + '/api/tracks', {
|
||||
"name": "string",
|
||||
"distance": 1500
|
||||
}, axios_config);
|
||||
expect(res.status).toEqual(200);
|
||||
expect(res.headers['content-type']).toContain("application/json")
|
||||
});
|
||||
it('get should return 200', async () => {
|
||||
const res1 = await axios.get(base + '/api/tracks', axios_config);
|
||||
expect(res1.status).toEqual(200);
|
||||
expect(res1.headers['content-type']).toContain("application/json")
|
||||
let added_track = res1.data[res1.data.length - 1]
|
||||
added_track_id = added_track.id
|
||||
delete added_track.id
|
||||
expect(added_track).toEqual({
|
||||
"name": "string",
|
||||
"distance": 1500
|
||||
})
|
||||
})
|
||||
it('get should return 200', async () => {
|
||||
const res2 = await axios.put(base + '/api/tracks/' + added_track_id, {
|
||||
"id": added_track_id,
|
||||
"name": "apitrack",
|
||||
"distance": 5100
|
||||
}, axios_config);
|
||||
expect(res2.status).toEqual(200);
|
||||
expect(res2.headers['content-type']).toContain("application/json")
|
||||
})
|
||||
it('get should return 200', async () => {
|
||||
const res3 = await axios.get(base + '/api/tracks', axios_config);
|
||||
expect(res3.status).toEqual(200);
|
||||
expect(res3.headers['content-type']).toContain("application/json")
|
||||
let added_track2 = res3.data[res3.data.length - 1]
|
||||
delete added_track2.id
|
||||
expect(added_track2).toEqual({
|
||||
"name": "apitrack",
|
||||
"distance": 5100
|
||||
})
|
||||
});
|
||||
});
|
||||
90
src/tests/tracks/track_add.spec.ts
Normal file
90
src/tests/tracks/track_add.spec.ts
Normal file
@@ -0,0 +1,90 @@
|
||||
import axios from 'axios';
|
||||
import { config } from '../../config';
|
||||
const base = "http://localhost:" + config.internal_port
|
||||
|
||||
let access_token;
|
||||
let axios_config;
|
||||
|
||||
beforeAll(async () => {
|
||||
const res = await axios.post(base + '/api/auth/login', { username: "demo", password: "demo" });
|
||||
access_token = res.data["access_token"];
|
||||
axios_config = {
|
||||
headers: { "authorization": "Bearer " + access_token },
|
||||
validateStatus: undefined
|
||||
};
|
||||
});
|
||||
|
||||
|
||||
describe('POST /api/tracks illegally', () => {
|
||||
it('no distance input should return 400', async () => {
|
||||
const res = await axios.post(base + '/api/tracks', {
|
||||
"name": "string",
|
||||
}, axios_config);
|
||||
expect(res.status).toEqual(400);
|
||||
expect(res.headers['content-type']).toContain("application/json")
|
||||
});
|
||||
it('illegal distance input should return 400', async () => {
|
||||
const res = await axios.post(base + '/api/tracks', {
|
||||
"name": "string",
|
||||
"distance": -1
|
||||
}, axios_config);
|
||||
expect(res.status).toEqual(400);
|
||||
expect(res.headers['content-type']).toContain("application/json")
|
||||
});
|
||||
it('negative minimum lap time input should return 406', async () => {
|
||||
const res = await axios.post(base + '/api/tracks', {
|
||||
"name": "string",
|
||||
"distance": 200,
|
||||
"minimumLapTime": -1
|
||||
}, axios_config);
|
||||
expect(res.status).toEqual(406);
|
||||
expect(res.headers['content-type']).toContain("application/json")
|
||||
});
|
||||
});
|
||||
// ---------------
|
||||
describe('POST /api/tracks successfully', () => {
|
||||
it('creating a track with the minimum amount of parameters should return 200', async () => {
|
||||
const res = await axios.post(base + '/api/tracks', {
|
||||
"name": "testtrack",
|
||||
"distance": 200,
|
||||
}, axios_config);
|
||||
expect(res.status).toEqual(200);
|
||||
expect(res.headers['content-type']).toContain("application/json");
|
||||
delete res.data.id;
|
||||
expect(res.data).toEqual({
|
||||
"name": "testtrack",
|
||||
"distance": 200,
|
||||
"minimumLapTime": null
|
||||
})
|
||||
});
|
||||
it('creating a track with all parameters (optional set to null) should return 200', async () => {
|
||||
const res = await axios.post(base + '/api/tracks', {
|
||||
"name": "testtrack",
|
||||
"distance": 200,
|
||||
"minimumLapTime": null
|
||||
}, axios_config);
|
||||
expect(res.status).toEqual(200);
|
||||
expect(res.headers['content-type']).toContain("application/json");
|
||||
delete res.data.id;
|
||||
expect(res.data).toEqual({
|
||||
"name": "testtrack",
|
||||
"distance": 200,
|
||||
"minimumLapTime": null
|
||||
})
|
||||
});
|
||||
it('creating a track with all parameters should return 200', async () => {
|
||||
const res = await axios.post(base + '/api/tracks', {
|
||||
"name": "testtrack",
|
||||
"distance": 200,
|
||||
"minimumLapTime": 123
|
||||
}, axios_config);
|
||||
expect(res.status).toEqual(200);
|
||||
expect(res.headers['content-type']).toContain("application/json");
|
||||
delete res.data.id;
|
||||
expect(res.data).toEqual({
|
||||
"name": "testtrack",
|
||||
"distance": 200,
|
||||
"minimumLapTime": 123
|
||||
})
|
||||
});
|
||||
});
|
||||
53
src/tests/tracks/track_delete.spec.ts
Normal file
53
src/tests/tracks/track_delete.spec.ts
Normal file
@@ -0,0 +1,53 @@
|
||||
import axios from 'axios';
|
||||
import { config } from '../../config';
|
||||
const base = "http://localhost:" + config.internal_port
|
||||
|
||||
let access_token;
|
||||
let axios_config;
|
||||
|
||||
beforeAll(async () => {
|
||||
const res = await axios.post(base + '/api/auth/login', { username: "demo", password: "demo" });
|
||||
access_token = res.data["access_token"];
|
||||
axios_config = {
|
||||
headers: { "authorization": "Bearer " + access_token },
|
||||
validateStatus: undefined
|
||||
};
|
||||
});
|
||||
|
||||
// ---------------
|
||||
describe('DETELE track', () => {
|
||||
let added_track
|
||||
it('creating a track with the minimum amount of parameters should return 200', async () => {
|
||||
const res = await axios.post(base + '/api/tracks', {
|
||||
"name": "testtrack",
|
||||
"distance": 200,
|
||||
}, axios_config);
|
||||
expect(res.status).toEqual(200);
|
||||
expect(res.headers['content-type']).toContain("application/json");
|
||||
added_track = res.data
|
||||
});
|
||||
it('delete track', async () => {
|
||||
const res2 = await axios.delete(base + '/api/tracks/' + added_track.id, axios_config);
|
||||
expect(res2.status).toEqual(200);
|
||||
expect(res2.headers['content-type']).toContain("application/json")
|
||||
let deleted_track = res2.data
|
||||
delete deleted_track.id;
|
||||
expect(res2.data).toEqual({
|
||||
"name": "testtrack",
|
||||
"distance": 200,
|
||||
"minimumLapTime": null
|
||||
});
|
||||
});
|
||||
it('check if track really was deleted', async () => {
|
||||
const res3 = await axios.get(base + '/api/tracks/' + added_track.id, axios_config);
|
||||
expect(res3.status).toEqual(404);
|
||||
expect(res3.headers['content-type']).toContain("application/json")
|
||||
});
|
||||
});
|
||||
// ---------------
|
||||
describe('DELETE track (non-existant)', () => {
|
||||
it('delete', async () => {
|
||||
const res2 = await axios.delete(base + '/api/tracks/0', axios_config);
|
||||
expect(res2.status).toEqual(204);
|
||||
});
|
||||
});
|
||||
98
src/tests/tracks/track_update.spec.ts
Normal file
98
src/tests/tracks/track_update.spec.ts
Normal file
@@ -0,0 +1,98 @@
|
||||
import axios from 'axios';
|
||||
import { config } from '../../config';
|
||||
const base = "http://localhost:" + config.internal_port
|
||||
|
||||
let access_token;
|
||||
let axios_config;
|
||||
|
||||
beforeAll(async () => {
|
||||
const res = await axios.post(base + '/api/auth/login', { username: "demo", password: "demo" });
|
||||
access_token = res.data["access_token"];
|
||||
axios_config = {
|
||||
headers: { "authorization": "Bearer " + access_token },
|
||||
validateStatus: undefined
|
||||
};
|
||||
});
|
||||
|
||||
describe('adding + updating illegally', () => {
|
||||
let added_track;
|
||||
it('correct distance input should return 200', async () => {
|
||||
const res = await axios.post(base + '/api/tracks', {
|
||||
"name": "apitrack",
|
||||
"distance": 1500
|
||||
}, axios_config);
|
||||
expect(res.status).toEqual(200);
|
||||
expect(res.headers['content-type']).toContain("application/json");
|
||||
added_track = res.data;
|
||||
});
|
||||
it('update with negative distance should return 400', async () => {
|
||||
const res2 = await axios.put(base + '/api/tracks/' + added_track.id, {
|
||||
"id": added_track.id,
|
||||
"name": "apitrack",
|
||||
"distance": -1
|
||||
}, axios_config);
|
||||
expect(res2.status).toEqual(400);
|
||||
expect(res2.headers['content-type']).toContain("application/json")
|
||||
});
|
||||
it('update with negative laptime should return 406', async () => {
|
||||
const res2 = await axios.put(base + '/api/tracks/' + added_track.id, {
|
||||
"id": added_track.id,
|
||||
"name": "apitrack",
|
||||
"distance": 2,
|
||||
"minimumLapTime": -1
|
||||
}, axios_config);
|
||||
expect(res2.status).toEqual(406);
|
||||
expect(res2.headers['content-type']).toContain("application/json")
|
||||
});
|
||||
});
|
||||
// ---------------
|
||||
describe('adding + updating successfilly', () => {
|
||||
let added_track;
|
||||
it('correct distance input should return 200', async () => {
|
||||
const res = await axios.post(base + '/api/tracks', {
|
||||
"name": "apitrack2",
|
||||
"distance": 1500
|
||||
}, axios_config);
|
||||
expect(res.status).toEqual(200);
|
||||
expect(res.headers['content-type']).toContain("application/json");
|
||||
added_track = res.data;
|
||||
});
|
||||
it('valid name change should return 200', async () => {
|
||||
const res2 = await axios.put(base + '/api/tracks/' + added_track.id, {
|
||||
"id": added_track.id,
|
||||
"name": "apitrackk",
|
||||
"distance": 1500
|
||||
}, axios_config);
|
||||
expect(res2.status).toEqual(200);
|
||||
expect(res2.headers['content-type']).toContain("application/json")
|
||||
});
|
||||
it('valid distance change should return 200', async () => {
|
||||
const res2 = await axios.put(base + '/api/tracks/' + added_track.id, {
|
||||
"id": added_track.id,
|
||||
"name": "apitrack2",
|
||||
"distance": 5100
|
||||
}, axios_config);
|
||||
expect(res2.status).toEqual(200);
|
||||
expect(res2.headers['content-type']).toContain("application/json")
|
||||
});
|
||||
it('valid laptime change (to a set number) should return 200', async () => {
|
||||
const res2 = await axios.put(base + '/api/tracks/' + added_track.id, {
|
||||
"id": added_track.id,
|
||||
"name": "apitrack2",
|
||||
"distance": 5100,
|
||||
"minimumLapTime": 3
|
||||
}, axios_config);
|
||||
expect(res2.status).toEqual(200);
|
||||
expect(res2.headers['content-type']).toContain("application/json")
|
||||
});
|
||||
it('valid laptime change (to a set null) should return 200', async () => {
|
||||
const res2 = await axios.put(base + '/api/tracks/' + added_track.id, {
|
||||
"id": added_track.id,
|
||||
"name": "apitrack2",
|
||||
"distance": 5100,
|
||||
"minimumLapTime": null
|
||||
}, axios_config);
|
||||
expect(res2.status).toEqual(200);
|
||||
expect(res2.headers['content-type']).toContain("application/json")
|
||||
});
|
||||
});
|
||||
49
src/tests/tracks/tracks_get.spec.ts
Normal file
49
src/tests/tracks/tracks_get.spec.ts
Normal file
@@ -0,0 +1,49 @@
|
||||
import axios from 'axios';
|
||||
import { config } from '../../config';
|
||||
const base = "http://localhost:" + config.internal_port
|
||||
|
||||
let access_token;
|
||||
let axios_config;
|
||||
|
||||
beforeAll(async () => {
|
||||
const res = await axios.post(base + '/api/auth/login', { username: "demo", password: "demo" });
|
||||
access_token = res.data["access_token"];
|
||||
axios_config = {
|
||||
headers: { "authorization": "Bearer " + access_token },
|
||||
validateStatus: undefined
|
||||
};
|
||||
});
|
||||
|
||||
describe('GET /api/tracks sucessfully', () => {
|
||||
it('basic get should return 200', async () => {
|
||||
const res = await axios.get(base + '/api/tracks', axios_config);
|
||||
expect(res.status).toEqual(200);
|
||||
expect(res.headers['content-type']).toContain("application/json")
|
||||
});
|
||||
});
|
||||
// ---------------
|
||||
describe('GET /api/tracks illegally', () => {
|
||||
it('get for non-existant track should return 404', async () => {
|
||||
const res = await axios.get(base + '/api/tracks/-1', axios_config);
|
||||
expect(res.status).toEqual(404);
|
||||
expect(res.headers['content-type']).toContain("application/json")
|
||||
});
|
||||
});
|
||||
// ---------------
|
||||
describe('adding + getting tracks', () => {
|
||||
let added_track;
|
||||
it('correct distance input should return 200', async () => {
|
||||
const res = await axios.post(base + '/api/tracks', {
|
||||
"name": "string",
|
||||
"distance": 1000
|
||||
}, axios_config);
|
||||
added_track = res.data;
|
||||
expect(res.status).toEqual(200);
|
||||
expect(res.headers['content-type']).toContain("application/json")
|
||||
});
|
||||
it('check if track was added (no parameter validation)', async () => {
|
||||
const res = await axios.get(base + '/api/tracks/' + added_track.id, axios_config);
|
||||
expect(res.status).toEqual(200);
|
||||
expect(res.headers['content-type']).toContain("application/json");
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user