How do I process a query parameter using NestJS?

Viewed 9097

The subject line is pretty much it.

I have a NestJS-based REST API server. I want to process a query parameter like so:

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

I can't seem to work out how to have the controller process that.

right now I have:

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

but that always returns the completed todos, not the ones where complete = false.

Here's the call to getTodosWithComlete:

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

How do I return the proper todos based on a query parameter?

1 Answers

By default all query parameters is string. If you want to have a boolean injected in your function getTodos you can use pipe classes to transform your parameters. According to https://docs.nestjs.com/pipes, there are already some built in pipes in NestJS, one of them is called ParseBoolPipe

So need to inject it in the Query decorator as second argument

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