DTOs
Part of the TypeScript and NestJS section of Coddy's Node.js journey. Lesson 10 of 17.
@Body() body: { title: string } describes the body in one place only, and nothing checks it: { "title": 42 } goes straight through. A DTO, a data transfer object, is a class that describes what a request body holds.
export class CreateOrderDto {
customer: string;
express?: boolean;
}
@Post()
create(@Body() dto: CreateOrderDto) {
return this.ordersService.create(dto);
}express? marks an optional field. The controller and the service share the class, so they agree on the shape.
A DTO is a class, not an interface, for a reason. Interfaces are removed with the other types when the code runs, while a class still exists, and only class-validator decorators on a class can check a body at run time. That is the next lesson.
Challenge
Easy- Fill
CreateTaskDtoindto/create-task.dto.ts: atitle, and an optionaldone. - Use it for the body of
POST /tasks. A new task takesdonefrom the body,falsewhen it is absent. - Send
POST /taskswith{ "title": "Pay rent", "done": true }, then with{ "title": 42 }.
Try it yourself
// Describe the body of POST /tasks: a title, and done when the client sends it.
export class CreateTaskDto {}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.