29 lines
862 B
TypeScript
29 lines
862 B
TypeScript
|
import {RequestHandler} from "express";
|
||
|
import {NextFunction, Request, Response} from "express-serve-static-core";
|
||
|
import Application from "./Application";
|
||
|
|
||
|
export default abstract class Middleware {
|
||
|
public constructor(
|
||
|
protected readonly app: Application,
|
||
|
) {
|
||
|
}
|
||
|
|
||
|
|
||
|
protected abstract async handle(req: Request, res: Response, next: NextFunction): Promise<void>;
|
||
|
|
||
|
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);
|
||
|
}
|
||
|
};
|
||
|
}
|
||
|
}
|