将管道应用于控制器中的所有可变事件

时间:2019-11-07 08:22:02

标签: typescript rest nestjs

我有一个具有多个请求(POST,GET等)的控制器。 对于所有这些,在路径中我都有一个id参数。我想验证该参数是否为数字字符串,但只想执行一次并将其应用于所有参数。

当前,这是我拥有的代码:

  @Get(':account_id')
  @ApiOperation({
    description: 'Get account information',
    operationId: 'getAccount',
    title: 'Get account information',
  })
  @ApiOkResponse({ type: AccountDto })
  @ApiUnauthorizedResponse({ type: ApiErrorDto })
  @ApiForbiddenResponse({ type: ApiErrorDto })
  @ApiNotFoundResponse({ type: ApiErrorDto })
  @ApiBadRequestResponse({ type: ApiErrorDto })
  @ApiImplicitParam({ name: 'account_id', description: 'The account Id' })
  async findOne(@Param('account_id', new ParseIntPipe()) accountId: string): Promise<AccountDto> {
    return await this.accountService.findOne(accountId);
  }

每次我都需要调用验证管道。

我是否可以将验证应用于控制器中的所有account_id变量?

1 个答案:

答案 0 :(得分:1)

您可以获取一个类作为您的参数,并对其属性进行验证。

控制器-

@Get(':id')
findOne(@Param() params: FindOneParams) {
  return params.id;
}

班级-

import { IsNumberString } from 'class-validator';

export class FindOneParams {
  @IsNumberString()
  id: number;
}
相关问题