Creating and Using DTOs
Veeg om het menu te tonen
Create a new file in the src folder:
create-user.dto.ts
Add the following code:
export class CreateUserDto {
name: string;
age: number;
}
This DTO defines the structure of the data your application expects.
Now use it in your controller:
import { Controller, Post, Body } from '@nestjs/common';
import { CreateUserDto } from './create-user.dto';
@Controller('users')
export class UsersController {
@Post()
createUser(@Body() body: CreateUserDto) {
return body;
}
}
Here is what is happening:
CreateUserDto: defines required fields;@Body(): extracts request data;CreateUserDto: ensures the data follows the defined structure.
Now send a request with data:
{
"name": "Alice",
"age": 30
}
The controller receives structured data based on the DTO.
Using DTOs keeps your data consistent and avoids repeating type definitions across your application.
Was alles duidelijk?
Bedankt voor je feedback!
Sectie 5. Hoofdstuk 3
Vraag AI
Vraag AI
Vraag wat u wilt of probeer een van de voorgestelde vragen om onze chat te starten.
Sectie 5. Hoofdstuk 3