Middlewares

@Middleware() is similar to the Express middleware with the difference that it's a class and you can use the IoC to inject other services on his constructor.

All middlewares decorated by @Middleware or @MiddlewareError have one method named use(). This method can use all parameters decorators as you could see with the Controllers and return promise.

Installation

To begin, you must adding the middlewares folder on componentsScan attribute in your server settings as follow :

import {ServerLoader} from "@tsed/common";
import Path = require("path");
const rootDir = Path.resolve(__dirname);

@ServerSettings({
   rootDir,
   mount: {
      '/rest': `${rootDir}/controllers/**/**.js`
   },
   componentsScan: [
       `${rootDir}/services/**/**.js`,
       `${rootDir}/middlewares/**/**.js`
   ]
})
export class Server extends ServerLoader {

}

Then, create a new file in your middlewares folder. Create a new Class definition then add the @Middleware() or @MiddlewareError() annotations on your class.

You have different use cases to declare and use a middleware. Theses use cases are following:

Specifics parameters decorators

In addition, you have this specifics parameters decorators for the middlewares:

Signature Example Description
@Err() useMethod(@Err() err: any) {} Inject the Express.Err service. (Decorator for middleware).
@ResponseData() useMethod(@ResponseData() data: any) Provide the data returned by the previous middlewares.
@EndpointInfo() useMethod(@EndpointInfo() endpoint: Endpoint) Provide the endpoint settings.