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 {
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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:
- Global Middleware, this middleware can be used on ServerLoader,
- Global MiddlewareError, this middleware error can be used on ServerLoader,
- Endpoint Middleware, this middleware can be used on a controller method,
- Endpoint Middleware Error, this middleware can be used on a controller method.
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. |
← Converters Scope →