Creating DTOs

Learn how DTOs enable structured and consistent data transfer between application layers.

Before moving to the endpoint related to book creation, we must first understand data transfer objects (DTOs). In this section, we’ll delve into the role of a DTO, explain its importance, and define a valid DTO that will be useful for creating and updating book entries in our system.

Scenario: Creating a student

Consider a scenario within a student management system. It starts with the basics. A StudentsService exists with a createStudent method. This method accepts two parameters: fullName and age, and returns a string message upon creating a student.

Press + to interact
@Injectable()
export class StudentsService {
createStudent(fullName: string, age: number) {
return `Student ${fullName} of age ${age} created!`;
}
}

In the StudentsController, a create method receives fullName and age from the request body and transfers them to the createStudent method of StudentsService.

Press + to interact
@Controller('students')
export class StudentsController {
constructor(private readonly studentsService: StudentsService) { }
@Post()
create(@Body() studentData: { fullName: string, age: number }) {
return this.studentsService.createStudent(studentData.fullName, studentData.age);
}
}
...