Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I process a query parameter using NestJS?

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?

like image 660
Nick Hodges Avatar asked Jul 20 '26 14:07

Nick Hodges


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;
 }
like image 140
Maxence Guyonvarho Avatar answered Jul 23 '26 05:07

Maxence Guyonvarho



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!