2020-09-25 22:03:22 +02:00
|
|
|
import {RequestHandler} from "express";
|
|
|
|
import {NextFunction, Request, Response} from "express-serve-static-core";
|
|
|
|
import Application from "./Application";
|
2020-09-25 23:42:15 +02:00
|
|
|
import {Type} from "./Utils";
|
2020-09-25 22:03:22 +02:00
|
|
|
|
|
|
|
export default abstract class Middleware {
|
|
|
|
public constructor(
|
|
|
|
protected readonly app: Application,
|
|
|
|
) {
|
|
|
|
}
|
|
|
|
|
|
|
|
|
2020-12-04 14:42:09 +01:00
|
|
|
protected abstract handle(req: Request, res: Response, next: NextFunction): Promise<void>;
|
2020-09-25 22:03:22 +02:00
|
|
|
|
|
|
|
public getRequestHandler(): RequestHandler {
|
|
|
|
return async (req, res, next): Promise<void> => {
|
|
|
|
try {
|
|
|
|
if (req.middlewares.find(m => m.constructor === this.constructor)) {
|
|
|
|
next();
|
|
|
|
} else {
|
|
|
|
req.middlewares.push(this);
|
|
|
|
return await this.handle(req, res, next);
|
|
|
|
}
|
|
|
|
} catch (e) {
|
|
|
|
next(e);
|
|
|
|
}
|
|
|
|
};
|
|
|
|
}
|
|
|
|
}
|
2020-09-25 23:42:15 +02:00
|
|
|
|
|
|
|
export interface MiddlewareType<M extends Middleware> extends Type<M> {
|
|
|
|
new(app: Application): M;
|
|
|
|
}
|