Nestjs:无法在同一控制器中实现多个 GET 方法

Joh*_*nny 1 node.js swagger nestjs

我这里有一些奇怪的问题。我有2种获取方法,一种是通过companyId获取员工列表,一种是通过staffId获取员工详细信息。第二种方法getStaffById不行。如果我注释掉第一个 get 方法getStaffByCompanyId,第二个方法将按预期工作。看起来第一个 get 方法阻止了第二个方法。我在这里错过了什么吗?

@Controller('staff')
@ApiTags('Staff')
export class StaffController {
  constructor(private staffService: StaffService) {}

  @Get(':companyId')
  @ApiResponse({
    status: HttpStatus.OK,
    description: 'Return staffs by id',
  })
  @ApiResponse({
    status: HttpStatus.UNAUTHORIZED,
    description: 'Unauthorized',
    type: Error,
  })
  @ApiResponse({
    status: HttpStatus.UNPROCESSABLE_ENTITY,
    description: 'Get particular staff details',
    type: Error,
  })
  @ApiResponse({
    status: HttpStatus.INTERNAL_SERVER_ERROR,
    description: 'Internal server error',
    type: Error,
  })
  @ApiResponse({
    status: HttpStatus.BAD_GATEWAY,
    description: 'Internal communication error',
    type: Error,
  })
  @ApiOperation({
    operationId: 'getStaffByCompanyId',
    summary: 'Get staff list that attach to the company',
  })
  async getStaffByCompanyId(@Param('companyId') companyId: string): Promise<IStaff[]> {
    return await this.staffService.getStaffByCompanyId(companyId);
  }

  @Get(':staffId')
  @ApiResponse({
    status: HttpStatus.OK,
    description: 'Return staff by id',
  })
  @ApiResponse({
    status: HttpStatus.UNAUTHORIZED,
    description: 'Unauthorized',
    type: Error,
  })
  @ApiResponse({
    status: HttpStatus.UNPROCESSABLE_ENTITY,
    description: 'Get particular staff details',
    type: Error,
  })
  @ApiResponse({
    status: HttpStatus.INTERNAL_SERVER_ERROR,
    description: 'Internal server error',
    type: Error,
  })
  @ApiResponse({
    status: HttpStatus.BAD_GATEWAY,
    description: 'Internal communication error',
    type: Error,
  })
  @ApiOperation({
    operationId: 'getStaffById',
    summary: 'Get staff profile details',
  })
  async getStaffById(@Param('staffId') staffId: string): Promise<IStaff> {
    return await this.staffService.getStaffById(staffId);
  }
}


Run Code Online (Sandbox Code Playgroud)

Jay*_*iel 6

Express(Nest 最有可能在后台为您使用的内容)无法区分

app.get('/:companyId', (req, res, next) => {})
Run Code Online (Sandbox Code Playgroud)

app.get('/:staffId', (req, res, next) => {})
Run Code Online (Sandbox Code Playgroud)

因为它所能看到的只是将有一个请求,其中某种通用参数以字符串形式传入,因此虽然您可能知道 acompanyId以 a 开头, CastaffId以 an 开头S,但无法将其告诉 Express,正因为如此,也没有办法让 Nest 告诉 Express。你能做的最好的事情就是在你的路由中添加一个像/comapny/:companyId和 这样的前缀/staff/:staffId,以确保它们保持分离。