diff --git a/src/controllers/Routes.ts b/src/controllers/Routes.ts index c5acadb..9d8f36a 100644 --- a/src/controllers/Routes.ts +++ b/src/controllers/Routes.ts @@ -16,7 +16,7 @@ export enum RouteType { export interface Route { type ?: RouteType, path: string, - cb: (req : RequestHandler) => void, + cb: (req : RequestHandler) => Promise | void, } export const Routes : Route[] = [ diff --git a/src/entities/RequestHandler.ts b/src/entities/RequestHandler.ts index ea8a3f8..f3a14d2 100644 --- a/src/entities/RequestHandler.ts +++ b/src/entities/RequestHandler.ts @@ -12,6 +12,8 @@ import { checkMail } from "../utils/StringUtils"; export class RequestHandler { private client : APIClient = null; + + private responseSent = false; public constructor(private req : Request, private response : Response) {} @@ -113,6 +115,10 @@ export class RequestHandler { * @param message The message to send */ public error(code : number, message : string) { + + if(this.responseSent) + return; + this.response.status(code).send({ error: { code: code, @@ -120,6 +126,8 @@ export class RequestHandler { } }); + this.responseSent = true; + throw Error("Could not complete request!"); } @@ -129,6 +137,9 @@ export class RequestHandler { * @param message Message associated to success */ public success(message: string) { + + this.responseSent = true; + this.response.send({ success: message }); @@ -140,6 +151,9 @@ export class RequestHandler { * @param data The data to send back to the server */ public send(data: any) { + + this.responseSent = true; + this.response.send(data); } } \ No newline at end of file diff --git a/src/main.ts b/src/main.ts index eea36ff..6155f5d 100644 --- a/src/main.ts +++ b/src/main.ts @@ -32,11 +32,19 @@ async function init() { const cb = async (req : express.Request, res : express.Response)=> { const handler = new RequestHandler(req, res); - // Check API tokens - await handler.checkAPITokens(); + try { + // Check API tokens + await handler.checkAPITokens(); - route.cb(handler); + const cb = route.cb(handler); + if(cb) + await cb; + + } catch(e) { + console.error(e); + handler.error(500, "Internal error."); + } }; if(route.type == RouteType.GET)