【问题标题】:Nestjs: Cant implement mutiple GET methods in same controllerNestjs:无法在同一控制器中实现多个 GET 方法
【发布时间】:2021-04-06 07:09:02
【问题描述】:

我这里有一些奇怪的问题。我有 2 种获取方法,一种是通过 companyId 获取员工列表并通过 StaffId 获取员工详细信息。第二种方法getStaffById 不起作用。如果我注释掉第一个获取方法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);
  }
}


【问题讨论】:

  • 要添加到 Jay 响应中,您必须阅读 REST API 中的“资源”概念。因为员工和公司是不同的对象,他们应该有不同的路径

标签: node.js swagger nestjs


【解决方案1】:

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

app.get('/:companyId', (req, res, next) => {})

app.get('/:staffId', (req, res, next) => {})

因为它所能看到的只是会有一个请求,带有某种通用参数作为字符串进来,所以虽然你可能知道companyIdC 开头,staffId 开头对于S,没有办法告诉 Express,因此,也没有办法告诉 Nest 告诉 Express。您可以做的最好的事情是在您的路线中添加像 /comapny/:companyId/staff/:staffId 这样的前缀,以确保它们保持分开。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-15
    • 1970-01-01
    • 2017-05-19
    相关资源
    最近更新 更多