2020-04-09 12:29:30 +02:00
|
|
|
import { Request, Response } from 'express';
|
|
|
|
import { http } from '@scode/consts';
|
2020-04-09 09:14:54 +02:00
|
|
|
import Transaction from './Transaction';
|
2020-04-08 20:46:48 +02:00
|
|
|
|
|
|
|
export default abstract class Handler {
|
2020-04-09 12:29:30 +02:00
|
|
|
private _handlers: Array<Function> = [];
|
2020-04-08 20:46:48 +02:00
|
|
|
private _method_handlers: Record<string, Function> = {};
|
|
|
|
|
2020-04-09 12:29:30 +02:00
|
|
|
protected register_handler (f: Function, method?: string): void {
|
2020-04-09 21:12:36 +02:00
|
|
|
if (typeof method === 'undefined') {
|
|
|
|
this._handlers.push (f);
|
|
|
|
}
|
2020-04-09 12:29:30 +02:00
|
|
|
else {
|
|
|
|
const m = method.toUpperCase ();
|
|
|
|
if (typeof this._method_handlers[m] !== 'undefined')
|
|
|
|
throw new Error (`Handler for ${m} already registered`);
|
|
|
|
this._method_handlers[m] = f;
|
|
|
|
}
|
2020-04-08 20:46:48 +02:00
|
|
|
}
|
|
|
|
|
2020-04-09 21:12:36 +02:00
|
|
|
private async run_method_handler (
|
|
|
|
method: string,
|
|
|
|
t: Transaction
|
|
|
|
): Promise<void> {
|
2020-04-08 20:46:48 +02:00
|
|
|
const m = method.toUpperCase ();
|
|
|
|
if (typeof this._method_handlers[m] !== 'undefined')
|
|
|
|
await this._method_handlers[m] (t);
|
|
|
|
}
|
|
|
|
|
2020-04-09 12:29:30 +02:00
|
|
|
public async run_http_handler (req: Request, res: Response): Promise<void> {
|
2020-04-08 20:46:48 +02:00
|
|
|
const t = new Transaction (req, res);
|
|
|
|
for (const handler of this._handlers) {
|
|
|
|
// eslint-disable-next-line no-await-in-loop
|
|
|
|
if (await handler (t) === false) {
|
2020-04-09 12:29:30 +02:00
|
|
|
if (!t.has_status)
|
|
|
|
t.status = http.status_internal_server_error;
|
2020-04-08 20:46:48 +02:00
|
|
|
t.finalize ();
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
await this.run_method_handler ('ALL', t);
|
|
|
|
await this.run_method_handler (t.req.method, t);
|
|
|
|
}
|
|
|
|
|
|
|
|
public abstract get path(): string;
|
|
|
|
}
|