Enhancing the API with Filters and Specific Modifiers

Enhancing the API with Filters and Specific Modifiers

Welcome to this lesson on enhancing your Todo REST API with filters and specific modifiers using NestJS. So far, we've covered the basics of setting up GET, POST, PUT, and DELETE requests which allows you to Create, Retrieve, Update, and Delete (CRUD) Todo items.

In this lesson, we'll build on those foundations by adding filters and specific modifiers to our API. You'll learn how to implement a filter to show only incomplete tasks and a modifier to mark tasks as complete. These features will make your API more flexible and powerful.

Adding Filters to the Todo API

Filters allow users to retrieve specific subsets of data, making the API more versatile. Imagine a case where the client only wants to see the incomplete Todo items. In this section, we'll add a filter to show only incomplete Todo items using query parameters.

Introduction to Query Parameters

Query parameters are used to pass optional information to a web API. They are appended to the URL and can be accessed in the request handler. In practice, they are added to the URL and may look familiar to you. Let's say you want to list all of the Todos that are incomplete, we can support a filter in the GET requiest such as GET /todos?showIncomplete=1 via the query parameter.

We'll add a showIncomplete filter to our findAll method in the TodoController and TodoService.

Code Example: `findAll` Method in `TodoController`

// src/todo/todo.controller.ts
@Controller('todos')
export class TodoController {
  constructor(private readonly todoService: TodoService) {}

  @Get()
  findAll(
    // Introduce the query parameter called showIncomplete
    @Query('showIncomplete') showIncomplete: boolean,
  ): TodoDto[] {
    // Pass the parameter along to the service
    return this.todoService.findAll(showIncomplete);
  }
  
  // ... Existing GET, POST, PUT, and DELETE handlers
}

Code Example: `findAll` Method in `TodoService`

// src/todo/todo.service.ts
@Injectable()
export class TodoService {
  private todos: TodoDto[] = [];

  findAll(showIncomplete?: boolean): TodoDto[] {
    if (showIncomplete) {
      return this.todos.filter(todo => !todo.completed);
    }
    
    return this.todos;
  }
  
  // ... Existing findOne, create, update, and delete methods
}
Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal