1 | import * as express from "express";
|
2 | import App from "./app";
|
3 | import StatusError from "./status-error";
|
4 |
|
5 | export const BLOCK_CHAIN = "__block_chain";
|
6 |
|
7 | /**
|
8 | * This class defines the base middleware class. Any middleware should be extends
|
9 | * this abstract class, implementing the apply method.
|
10 | */
|
11 | export abstract class BaseMiddleware {
|
12 | public app: App;
|
13 |
|
14 | constructor(app: App) {
|
15 | this.app = app;
|
16 | }
|
17 |
|
18 | /**
|
19 | * Utility method to generate an error with a status code.
|
20 | * This method should be used instead of the usual throw new Error(msg).
|
21 | * In this way, a proper HTTP status code can be used (for example, 404 or 500),
|
22 | * instead of the default 400.
|
23 | * @param status the http status code to return
|
24 | * @param message the error message
|
25 | * @return a new @type StatusError object
|
26 | */
|
27 | public error(status: number, message: string): StatusError {
|
28 | let err = new StatusError(message);
|
29 | err.statusCode = status;
|
30 | return err;
|
31 | }
|
32 |
|
33 | /**
|
34 | * This method is automatically executed by the framework.
|
35 | * @param req the standard express Request object
|
36 | * @param res the standard express Response object
|
37 | * @return to block the middlewares-controller chain, please return `BLOCK_CHAIN`
|
38 | */
|
39 | abstract async apply(
|
40 | req: express.Request,
|
41 | res: express.Response
|
42 | ): Promise<any>;
|
43 | }
|