在nestjs中可以在一种方法上使用多个装饰符吗?

我想编写更少的代码,所以我将创建和更新代码合并到一个方法中,看起来它无法工作。

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

我试过了,但这里只有@Post装饰符可以使用。


解决方案

您可以使用@All修饰符在一个方法中处理所有请求方法:

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

如果您在@All('user')处理程序之前定义了@Get('user')处理程序,它将处理GET请求。(我建议不要这样做,见下文。)


建议

1)通过使用@Res注入框架特定的响应对象,您将失去使Nest如此出色的大部分特性,例如拦截器或序列化。只有在您确实需要时才这样做。

2)我总是更喜欢将公共逻辑提取到方法或类中,而不是在方法中创建条件分支。在我看来,这是一种更具可读性和可维护性的方法。它还简化了其他嵌套集成,例如使用swagger轻松记录您的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);
}

在此示例中,公共部分被提取到UserService#prepare中。

相关文章