简体   繁体   中英

Create a custom NestJs Decorator inheriting @Body() or @Param() decorator?

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) {
    // ... 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM