Menu
CoddyTech

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 icon

Challenge

Easy
  • Fill CreateTaskDto in dto/create-task.dto.ts: a title, and an optional done.
  • Use it for the body of POST /tasks. A new task takes done from the body, false when it is absent.
  • Send POST /tasks with { "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 {}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in TypeScript and NestJS