Building a To-Do REST API with NestJS - Create a ToDo Item Provided from the Request Body
Creating new Todo Items in the Controller
import{ Body, Controller, Post }from'@nestjs/common';import{ CreateTodoDto, TodoDto }from'./todo.dto';import{ TodoService }from'./todo.service';@Controller('todos')exportclassTodoController{constructor(privatereadonly todoService: TodoService){}// ... Existing GET handlers@Post()create(// Decorate this data object with @Body() to declare that the data comes// from the HTTP body and not the URL@Body() todo: CreateTodoDto,): TodoDto {returnthis.todoService.createTodo(todo);}}
Implementing the TodoService
import{ Injectable }from'@nestjs/common';import{ CreateTodoDto, TodoDto }from'./todo.dto';@Injectable()exportclassTodoService{private todos: TodoDto[]=[];// ... existing fetch methodscreateTodo(todo: CreateTodoDto): TodoDto {// `CreateTodoDto` is a subset of the `TodoDto`. It only includes the title and// description so we need to populate the `id` and `completed` fieldsconst newTodo ={
id: global.crypto.randomUUID(),...todo,
completed:false,};this.todos.push(newTodo);return newTodo;}}