Kent Wood
Kent Wood

Reputation: 1522

is it possible to use multi decorators on one method in nestjs?

I want to write less code, so I combine create and update code into one method, looks it can not work.

@Post('user')
@Put('user')
async createOrUpdateUser(@Res() res, @Req() req) {
  if (req.method == 'POST') {
    //do user creating work
  } else {
    //do user updating work
  }
}

I've tried it, but only the @Post decorator works here.

Upvotes: 5

Views: 4914

Answers (2)

Kim Kern
Kim Kern

Reputation: 60357

You can use the @All decorator to handle all request methods in one method:

@All('user')
async createOrUpdateUser(@Req() req) {
  switch (req.method) {
    case 'POST':
      return 'new user';
    case 'PUT':
      return 'updated user';
    default:
      return throw new NotFoundException();
  }
}

If you a define a @Get('user') handler before the @All('user') handler, it will handle the get requests. (I'd advice against doing that, see below.)


Advice

1) By injecting the framework specific response object with @Res, you'll lose most of the features that make nest so great such as interceptors or serialization. Only do that, if you really need to.

2) I always prefer to extract common logic into a method or class instead of creating conditional branches within a method. In my opinion, this is a more readable and maintainable approach. It also makes other nest integrations easier for example using swagger to easily document your API.

@Put('user')
async update(@Body() body) {
  const user = await this.service.prepare(body);
  return this.service.updateUser(user);
}

@Post('user')
async update(@Body() body) {
  const user = await this.service.prepare(body);
  return this.service.createUser(user);
}

In this example, the common parts were extracted into UserService#prepare.

Upvotes: 7

Igor Litvinovich
Igor Litvinovich

Reputation: 2502

It doesn't seem to be working like that, but you can do it as following so that you can avoid duplication.

@Post('user')
async createUser(@Res() res, @Req() req) {
  if(req.method=='POST')
  {
    //do user creating work
  }else {
    //do user updating work
  }
}

@Put('user')
async updateUser(@Res() res, @Req() req) {
 this.createUser(res, req);
}

Upvotes: 1

Related Questions