# Filters
Filters feature lets you create custom decorators that will be used on the methods parameters like or .
# Example
This example shows you how you can implement a filter and decorator to use these, on a method Controller. In this case, we need to retrieve the body content from an Express.Request.
So to do that, you must create a class and annotate it with the decorator and in option, implement the interface:
import {Filter, IFilter, ParseService} from "@tsed/common";
import * as Express from "express";
@Filter()
export class CustomBodyParamFilter implements IFilter {
constructor(private parseService: ParseService) {
}
transform(expression: string, request: Express.Request, response: Express.Response) {
return this.parseService.eval(expression, request["body"]);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13
Then create the decorator. This decorator will be used on a controller method.
import {IParamOptions, ParamTypes, UseFilter} from "@tsed/common";
import {CustomBodyParamFilter} from "./CustomBodyParamFilter";
export function CustomBodyParams(options: IParamOptions<any> = {}): ParameterDecorator {
const {expression, useType, useConverter = true, useValidation = true} = options;
return UseFilter(CustomBodyParamFilter, {
expression,
useType,
useConverter,
useValidation,
paramType: ParamTypes.BODY // for swagger
});
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
6
7
8
9
10
11
12
13
14
And finally you can use your custom filter on your controller/middleware:
import {Controller, Post} from "../../../../packages/common/src/mvc/decorators";
import {CustomBodyParams} from "./filter-decorator";
@Controller("/")
export class MyController {
@Post("/")
save(@CustomBodyParams({}) payload: any) {
console.log(payload);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
# UseFilter Options
deprecatedallows you to register your custom decorator with few options as following:
paramType
(ParamTypes): Parameter type like BODY, QUERY, PARAMS, etc...,required
(boolean, optional): Throw an error if the value is undefined,expression
(string, optional): An expression to parse,useConverter
(boolean): Enable json mapper to deserialize value,useValidation
(boolean): Enable validation,useType
(boolean): Set explicitly the class/model used by the parameters.
- Session & cookies
- Passport.js
- TypeORM
- Mongoose
- GraphQL
- Socket.io
- Swagger
- AJV
- Multer
- Serve static files
- Templating
- Throw HTTP Exceptions
- Customize 404
- AWS
- Jest
- Seq
- Controllers
- Providers
- Model
- Converters
- Middlewares
- Pipes
- Interceptors
- Authentication
- Hooks
- Injection scopes
- Custom providers
- Custom endpoint decorator
- Testing