Global middleware

Global middlewares and Endpoint middlewares are almost similar but Global middleware cannot use the . Global middlewares lets you manage request and response on .

Usage

Create your middleware:

import {IMiddleware, Middleware, Req, ServerSettingsService} from "@tsed/common";
import {NotAcceptable} from "ts-httpexceptions";

@Middleware()
export default class GlobalAcceptMimesMiddleware implements IMiddleware {
  constructor(private serverSettingsService: ServerSettingsService) {
  }

  use(@Req() request: Req) {
    this.serverSettingsService.acceptMimes
      .forEach((mime) => {
        if (!request.accepts(mime)) {
          throw new NotAcceptable(mime);
        }
      });
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

Then, add your middleware in :

import {ServerLoader, ServerSettings} from "@tsed/common";
import {GlobalAcceptMimeMiddleware} from "./GlobalAcceptMimeMiddleware";

const rootDir = __dirname;

@ServerSettings({
  rootDir,
  componentsScan: [
    `${rootDir}/middlewares/**/**.js`
  ],
  acceptMimes: ["application/json"]  // add your custom configuration here
})
export class Server extends ServerLoader {
  $beforeRoutesInits() {
    this.use(GlobalAcceptMimeMiddleware);
  }

  // or
  $afterRoutesInit() {
    this.use(GlobalAcceptMimeMiddleware); // But maybe is too late ;)
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

Handle error

Express allows you to handle any error when your middleware have 4 parameters like this:

function (error, req, res, next){}
1

Ts.ED has the same mechanism with decorator. The following example is the GlobalErrorHandlerMiddleware used by Ts.ED to handle all errors throw by your application.

import {Err, Middleware, Req, Res} from "@tsed/common";
import {Exception} from "ts-httpexceptions";
import {$log} from "ts-log-debug";

@Middleware()
export class GlobalErrorHandlerMiddleware {
  use(
    @Err() error: any,
    @Req() request: Req,
    @Res() response: Res
  ): any {

    if (response.headersSent) {
      throw error;
    }

    const toHTML = (message = "") => message.replace(/\n/gi, "<br />");

    if (error instanceof Exception) {
      $log.error("" + error);
      response.status(error.status).send(toHTML(error.message));

      return;
    }

    if (typeof error === "string") {
      response.status(404).send(toHTML(error));

      return;
    }

    $log.error("" + error);
    response.status(error.status || 500).send("Internal Error");

    return;
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37