In NestJS, Data Transfer Objects (DTOs) are used to define the shape of data sent between client and server. Why does using DTOs help enforce data contracts?
Think about how defining a shape or schema helps catch errors early.
DTOs specify exactly what data is expected, so if data is missing or has extra fields, NestJS can catch it. This keeps data consistent and predictable.
Consider a NestJS controller method that expects a DTO with a required name string property. What will happen if the client sends a request missing the name field?
import { IsString } from 'class-validator'; export class CreateUserDto { @IsString() name: string; } @Post() createUser(@Body() createUserDto: CreateUserDto) { return `User ${createUserDto.name} created`; }
Think about how validation pipes work with DTOs in NestJS.
When validation pipes are used, NestJS checks the incoming data against the DTO. Missing required fields cause a 400 error response.
Choose the correct DTO class that enforces title as a required string and count as an optional number.
Look for correct use of decorators and optional property syntax.
Option A uses @IsString() for required title and @IsOptional() with @IsNumber() for optional count. Others have wrong types or missing decorators.
Given this DTO and controller, why does NestJS accept requests missing the email field?
import { IsEmail, IsString } from 'class-validator'; export class RegisterDto { @IsEmail() email: string; @IsString() password: string; } @Post('register') register(@Body() registerDto: RegisterDto) { return 'Registered'; }
Think about how validation is triggered in NestJS.
Validation decorators only work if ValidationPipe is enabled. Without it, DTOs are just plain classes and no validation happens.
Consider this DTO and controller with ValidationPipe configured with whitelist: true. What will the response contain if the client sends extra fields?
import { IsString } from 'class-validator'; export class UpdateProfileDto { @IsString() username: string; } @Post('update') updateProfile(@Body() updateProfileDto: UpdateProfileDto) { return updateProfileDto; } // ValidationPipe setup: // app.useGlobalPipes(new ValidationPipe({ whitelist: true }));
What does the whitelist option do in ValidationPipe?
With whitelist: true, ValidationPipe strips out any properties not defined in the DTO before passing the object to the controller.