Adding Filters to the Todo API
Updating findAll method in TodoController
import { Controller, Get, Query } from '@nestjs/common';
import { TodoDto } from './dtos/todo.dto';
import { TodoService } from './todo.service';
@Controller('todos')
export class TodoController {
constructor(private readonly todoService: TodoService) {}
@Get()
findAll(
@Query('showIncomplete') showIncomplete: boolean,
): TodoDto[] {
return this.todoService.findAll(showIncomplete);
}
}
Updating findAll method in TodoService
import { Injectable } from '@nestjs/common';
import { TodoDto } from './dtos/todo.dto';
@Injectable()
export class TodoService {
private todos: TodoDto[] = [];
findAll(showIncomplete?: boolean): TodoDto[] {
if (showIncomplete) {
return this.todos.filter((todo) => !todo.completed);
}
return this.todos;
}
}
Adding Specific Modifiers to the Todo API
- path parameters can be used to identify specific resources in an API (e.g.
/todos/:id/complete)
Adding complete method to TodoController
import { Controller, Param, Put } from '@nestjs/common';
import { TodoDto } from './dtos/todo.dto';
import { TodoService } from './todo.service';
@Controller('todos')
export class TodoController {
constructor(private readonly todoService: TodoService) {}
@Put(':id/complete')
complete(@Param('id') id: string): TodoDto {
return this.todoService.markTodoComplete(id);
}
}
Adding complete method to TodoService
import { Injectable } from '@nestjs/common';
import { TodoDto } from './dtos/todo.dto';
@Injectable()
export class TodoService {
private todos: TodoDto[] = [];
markTodoComplete(id: string): TodoDto | null {
return this.updateTodo(id, { completed: true });
}
}