[英]Create a custom NestJs Decorator inheriting @Body() or @Param() decorator?
I'm usin NestJs, and in many of my controllers I'm using : 我在NestJs中使用,在我使用的许多控制器中:
@Post(":id")
public create(
@Param('id', new ParseIntPipe()) id: number,
@Body(new ValidationPipe({transform: true})) myData: MyClass) {
// ...
}
I would like to clean my code by creating a custom decorator, for instance: 我想通过创建自定义装饰器来清理我的代码,例如:
@Bind() => @Body(new ValidationPipe({transform: true}))
or 要么
@Id() => @Param('id', new ParseIntPipe())
then the code would be much more cleaner than before: 然后代码会比以前更清晰:
@Post(":id")
public create(@Id() id: number, @Bind() myData: MyClass) {
// ...
}
What is the correct way to inherit those decorators like this? 继承像这样的装饰器的正确方法是什么?
Thanks 谢谢
Since decorators are just plain functions you can simply create a function that returns the called decorator: 由于装饰器只是普通函数,因此您只需创建一个返回被调用装饰器的函数:
decorators.ts decorators.ts
import { Body, Param, ParseIntPipe, ValidationPipe } from '@nestjs/common';
export const Bind = () => Body(
new ValidationPipe({transform: true}),
);
export const Id = () => Param('id', new ParseIntPipe());
And then use them as decorators: 然后将它们用作装饰器:
import { Id, Bind } from './decorators';
// ...
@Post(":id")
public create(@Id() id: number, @Bind() myData: MyClass) {
// ...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.