如何使用NestJS处理查询参数?

时间:2020-04-04 16:20:23

标签: typescript rest nestjs

主题行差不多。

我有一个基于NestJS的REST API服务器。我想像这样处理查询参数:

http://localhost:3000/todos?complete=false 

我似乎无法解决如何让控制器处理该问题。

现在我有:

  @Get()
  async getTodos(@Query('complete') isComplete: boolean) {
    const todosEntities = await this.todosService.getTodosWithComlete(isComplete);
    const todos = classToPlain(todosEntities);
    return todos;
  }

但这总是返回已完成的待办事项,而不是会返回complete = false的待办事项。

以下是getTodosWithComlete的电话:

  async getTodosWithComplete(isComplete?: boolean): Promise<Todo[]> {
    return this.todosRepository.find({
      complete: isComplete,
      isDeleted: false,
    });
  }

如何根据查询参数返回正确的todos

1 个答案:

答案 0 :(得分:1)

默认情况下,所有查询参数都是字符串。 如果要在函数getTodos中注入布尔值,则可以使用管道类来转换参数。 根据{{​​3}}的说法,NestJS中已经有一些内置管道,其中之一称为ParseBoolPipe

因此需要将其作为第二个参数注入Query装饰器中

@Get()
  async getTodos(@Query('complete', ParseBoolPipe) isComplete: boolean) {
    const todosEntities = await this.todosService.getTodosWithComlete(isComplete);
    const todos = classToPlain(todosEntities);
    return todos;
 }