3

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 Answer 1

6

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;
 }
Sign up to request clarification or add additional context in comments.

3 Comments

Oh, that is so much better. Thanks very much.
Well, interesting, the parameter as used above always returns true, no matter what is passed in the URL.
Since version 7, there are implicit param conversion, docs.nestjs.com/… But I never tested that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.