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

Typescript 如何使用NestJS处理查询参数?,typescript,rest,nestjs,Typescript,Rest,Nestjs,主题行差不多就是它 我有一个基于NestJS的RESTAPI服务器。我想处理如下查询参数: http://localhost:3000/todos?complete=false 我似乎不知道如何让控制器处理这个问题 现在我有: @Get() async getTodos(@Query('complete') isComplete: boolean) { const todosEntities = await this.todosService.getTodosWithComl

主题行差不多就是它

我有一个基于NestJS的RESTAPI服务器。我想处理如下查询参数:

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;
  }
但它总是返回已完成的TODO,而不是complete=false的TODO

下面是对
getTodosWithComlete
的调用:

  async getTodosWithComplete(isComplete?: boolean): Promise<Todo[]> {
    return this.todosRepository.find({
      complete: isComplete,
      isDeleted: false,
    });
  }
异步getToSwithComplete(isComplete?:布尔):承诺{ 返回this.todosRepository.find({ 完成:isComplete, isDeleted:错, }); }
如何根据查询参数返回正确的
TODO

默认情况下,所有查询参数都是字符串。 如果希望在函数getToOS中注入布尔值,可以使用管道类来转换参数。 据介绍,NestJS中已经有一些内置管道,其中一个叫做ParseBoolPipe

所以需要将其作为第二个参数注入查询装饰器中

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

哦,那好多了。非常感谢。嗯,有趣的是,上面使用的参数总是返回true,不管URL中传递了什么。自版本7以来,有隐式参数转换,但我从未测试过。