I'm usin NestJs, and in many of my controllers I'm using :
@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
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) {
// ...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With