Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 436
Daniel Santos Avatar asked Jun 23 '19 18:06

Daniel Santos


1 Answers

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) {
    // ... 
}
like image 128
Ghero Avatar answered Nov 10 '22 06:11

Ghero