Bird
Raised Fist0
NestJSframework~20 mins

Why DTOs enforce data contracts in NestJS - Challenge Your Understanding

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
DTO Mastery in NestJS
Get all challenges correct to earn this badge!
Test your skills under time pressure!
🧠 Conceptual
intermediate
2:00remaining
Why do DTOs help maintain consistent data in NestJS?

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?

ADTOs automatically encrypt data to secure it during transfer.
BDTOs define a fixed structure that incoming data must match, preventing unexpected or missing fields.
CDTOs allow any data shape, so developers can send flexible data without restrictions.
DDTOs replace the need for database models by storing data directly.
Attempts:
2 left
💡 Hint

Think about how defining a shape or schema helps catch errors early.

❓ component_behavior
intermediate
2:00remaining
What happens when invalid data is sent to a NestJS controller expecting a DTO?

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?

NestJS
import { IsString } from 'class-validator';

export class CreateUserDto {
  @IsString()
  name: string;
}

@Post()
createUser(@Body() createUserDto: CreateUserDto) {
  return `User ${createUserDto.name} created`;
}
ANestJS will crash the server with an unhandled exception.
BNestJS will accept the request and create a user with an undefined name.
CNestJS will ignore the missing field and fill it with an empty string.
DNestJS will throw a validation error and respond with a 400 Bad Request.
Attempts:
2 left
💡 Hint

Think about how validation pipes work with DTOs in NestJS.

📝 Syntax
advanced
2:00remaining
Which DTO definition correctly enforces a required string and optional number in NestJS?

Choose the correct DTO class that enforces title as a required string and count as an optional number.

A
import { IsString, IsNumber, IsOptional } from 'class-validator';

export class ItemDto {
  @IsString()
  title: string;

  @IsNumber()
  @IsOptional()
  count?: number;
}
B
export class ItemDto {
  title?: string;
  count: number;
}
C
export class ItemDto {
  @IsNumber()
  title: number;

  @IsString()
  count?: string;
}
D
export class ItemDto {
  @IsOptional()
  title: string;

  count: number;
}
Attempts:
2 left
💡 Hint

Look for correct use of decorators and optional property syntax.

🔧 Debug
advanced
2:00remaining
Why does this DTO validation not reject missing fields?

Given this DTO and controller, why does NestJS accept requests missing the email field?

NestJS
import { IsEmail, IsString } from 'class-validator';

export class RegisterDto {
  @IsEmail()
  email: string;

  @IsString()
  password: string;
}

@Post('register')
register(@Body() registerDto: RegisterDto) {
  return 'Registered';
}
AThe ValidationPipe is not enabled globally or on the route, so validation is skipped.
BThe <code>@IsEmail()</code> decorator is incorrect and does not validate the field.
CThe <code>email</code> property is optional by default, so missing is allowed.
DNestJS does not support validation on DTOs without explicit type annotations.
Attempts:
2 left
💡 Hint

Think about how validation is triggered in NestJS.

❓ state_output
expert
2:00remaining
What is the output when sending extra fields not in the DTO with ValidationPipe whitelist enabled?

Consider this DTO and controller with ValidationPipe configured with whitelist: true. What will the response contain if the client sends extra fields?

NestJS
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 }));
AServer crashes due to unexpected fields in the DTO.
B{"username":"newuser", "age":30} - extra fields are kept in the object.
C{"username":"newuser"} - extra fields are removed from the object.
DValidation error response because extra fields are not allowed.
Attempts:
2 left
💡 Hint

What does the whitelist option do in ValidationPipe?

Practice

(1/5)
1. Why do we use DTOs (Data Transfer Objects) in NestJS applications?
easy
A. To speed up the application runtime
B. To handle user interface styling
C. To replace database models completely
D. To define clear data shapes and enforce data contracts

Solution

  1. Step 1: Understand the purpose of DTOs

    DTOs are used to define the shape and structure of data that travels through the application.
  2. Step 2: Identify the main benefit in NestJS context

    They enforce data contracts, meaning they ensure data is consistent and validated before use.
  3. Final Answer:

    To define clear data shapes and enforce data contracts -> Option D
  4. Quick Check:

    DTOs = enforce data contracts [OK]
Hint: DTOs define data shape and rules clearly [OK]
Common Mistakes:
  • Thinking DTOs speed up runtime
  • Confusing DTOs with UI styling
  • Assuming DTOs replace database models
2. Which of the following is the correct way to define a simple DTO class in NestJS using TypeScript?
easy
A. interface CreateUserDto { name: string; age: number; }
B. class CreateUserDto { name: string; age: number; }
C. function CreateUserDto() { return { name: string, age: number }; }
D. const CreateUserDto = { name: 'string', age: 'number' };

Solution

  1. Step 1: Recall NestJS DTO syntax

    DTOs are usually defined as classes with typed properties in TypeScript.
  2. Step 2: Check each option's syntax

    class CreateUserDto { name: string; age: number; } correctly defines a class with typed properties. function CreateUserDto() { return { name: string, age: number }; } is a function, not a class. interface CreateUserDto { name: string; age: number; } is an interface, which can't be used for runtime validation. const CreateUserDto = { name: 'string', age: 'number' }; is an object literal with string values, not types.
  3. Final Answer:

    class CreateUserDto { name: string; age: number; } -> Option B
  4. Quick Check:

    DTO = class with typed properties [OK]
Hint: DTOs are classes with typed properties in NestJS [OK]
Common Mistakes:
  • Using interfaces instead of classes for DTOs
  • Defining DTOs as plain objects
  • Using functions instead of classes
3. Given this DTO and controller snippet, what will happen if the incoming request body misses the email property?
class RegisterDto {
  username: string;
  email: string;
}

@Post('register')
register(@Body() data: RegisterDto) {
  return data;
}
medium
A. The server will crash with a runtime error
B. The request will succeed and email will be undefined
C. The request will fail validation if validation pipes are used
D. The missing property will be automatically filled with an empty string

Solution

  1. Step 1: Understand DTO role with validation

    DTOs define expected data shape. If validation pipes are enabled, missing required properties cause validation errors.
  2. Step 2: Analyze behavior when email is missing

    Without email, validation fails and the request is rejected. If no validation, email would be undefined, but NestJS commonly uses validation pipes.
  3. Final Answer:

    The request will fail validation if validation pipes are used -> Option C
  4. Quick Check:

    Missing required DTO property = validation error [OK]
Hint: Missing required DTO fields cause validation errors if pipes used [OK]
Common Mistakes:
  • Assuming missing fields auto-fill with defaults
  • Thinking server crashes on missing fields
  • Ignoring validation pipes effect
4. Identify the error in this DTO usage that causes the validation to always pass even when data is invalid:
class UpdateProfileDto {
  name?: string;
  age?: number;
}

@Post('update')
update(@Body() data: UpdateProfileDto) {
  return data;
}
medium
A. DTO properties are optional, so validation does not enforce presence
B. DTO class is missing the @Injectable decorator
C. The controller method should use @Query instead of @Body
D. The DTO class must extend a base validation class

Solution

  1. Step 1: Review DTO property optionality

    Properties marked with ? are optional, so validation allows them to be missing.
  2. Step 2: Understand validation effect

    Because all properties are optional, invalid or missing data passes validation, which may be unintended.
  3. Final Answer:

    DTO properties are optional, so validation does not enforce presence -> Option A
  4. Quick Check:

    Optional DTO fields = no required validation [OK]
Hint: Optional properties skip required validation [OK]
Common Mistakes:
  • Thinking @Injectable is needed on DTOs
  • Confusing @Body with @Query usage
  • Assuming inheritance is required for validation
5. You want to ensure that a DTO enforces that the password field is always a string with at least 8 characters. Which approach best enforces this contract in NestJS?
hard
A. Use class-validator decorators like @IsString() and @MinLength(8) on the password property
B. Manually check the password length inside the controller method
C. Define password: string in the DTO without decorators
D. Use a plain JavaScript object instead of a class for the DTO

Solution

  1. Step 1: Understand validation decorators in NestJS

    Using class-validator decorators on DTO properties enforces rules automatically during validation.
  2. Step 2: Compare options for enforcing password rules

    Use class-validator decorators like @IsString() and @MinLength(8) on the password property uses decorators to enforce string type and minimum length. Manually check the password length inside the controller method requires manual checks, which is less clean. Define password: string in the DTO without decorators lacks validation. Use a plain JavaScript object instead of a class for the DTO loses type safety and validation.
  3. Final Answer:

    Use class-validator decorators like @IsString() and @MinLength(8) on the password property -> Option A
  4. Quick Check:

    Validation decorators enforce data contracts best [OK]
Hint: Use validation decorators on DTO properties [OK]
Common Mistakes:
  • Relying on manual validation in controllers
  • Skipping decorators and trusting types only
  • Using plain objects instead of classes
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard