Bird
Raised Fist0
NestJSframework~20 mins

Why pipes transform and validate input in NestJS - Challenge Your Understanding

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
NestJS Pipes Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
🧠 Conceptual
intermediate
1:30remaining
Purpose of Pipes in NestJS
What is the primary reason NestJS pipes transform and validate input data?
ATo delay the processing of requests until the server is less busy
BTo encrypt input data for security before processing
CTo automatically generate database queries from input data
DTo ensure input data meets expected format and types before reaching route handlers
Attempts:
2 left
💡 Hint
Think about how pipes help keep your application safe and predictable.
❓ component_behavior
intermediate
2:00remaining
Effect of Validation Pipe on Controller Input
Given a NestJS controller using a ValidationPipe, what happens if the input data does not match the DTO validation rules?
NestJS
import { Controller, Post, Body, UsePipes, ValidationPipe } from '@nestjs/common';
import { IsInt, Min } from 'class-validator';

class AgeDto {
  @IsInt()
  @Min(0)
  age: number;
}

@Controller('users')
export class UserController {
  @Post('age')
  @UsePipes(new ValidationPipe())
  setAge(@Body() ageDto: AgeDto) {
    return `Age set to ${ageDto.age}`;
  }
}
AThe request is rejected with a 400 Bad Request error and validation details
BThe input is accepted but logged as a warning
CThe controller sets age to zero by default and returns success
DThe server crashes due to unhandled validation errors
Attempts:
2 left
💡 Hint
ValidationPipe stops invalid data from reaching the controller.
📝 Syntax
advanced
1:30remaining
Correct Use of Transform in a Custom Pipe
Which option correctly implements a NestJS pipe that transforms a string input to uppercase before passing it to the handler?
NestJS
import { PipeTransform, Injectable, ArgumentMetadata } from '@nestjs/common';

@Injectable()
export class UppercasePipe implements PipeTransform {
  transform(value: any, metadata: ArgumentMetadata) {
    // Transform logic here
  }
}
Areturn value.uppercase();
Breturn value.toUpperCase();
Creturn value.toUpper();
Dreturn value.toUpperCase
Attempts:
2 left
💡 Hint
Check the correct JavaScript string method for uppercase conversion.
🔧 Debug
advanced
2:00remaining
Identifying Pipe Validation Error Cause
A NestJS app uses a ValidationPipe globally. A POST request with body {"age": "twenty"} is sent to a route expecting a DTO with @IsInt() age property. What error will occur and why?
A400 Bad Request because 'twenty' is not an integer
B500 Internal Server Error due to type mismatch
CRequest succeeds but age is set to 0
DNo error, input is accepted as string
Attempts:
2 left
💡 Hint
ValidationPipe enforces type and format rules strictly.
❓ state_output
expert
2:30remaining
Output of a Pipe Transforming and Validating Input
Consider this NestJS pipe that transforms input to a number and validates it is positive. What is the output when input is '-5'?
NestJS
import { PipeTransform, Injectable, BadRequestException } from '@nestjs/common';

@Injectable()
export class PositiveNumberPipe implements PipeTransform {
  transform(value: any) {
    const val = Number(value);
    if (isNaN(val) || val <= 0) {
      throw new BadRequestException('Value must be a positive number');
    }
    return val;
  }
}

// Usage in controller:
// @UsePipes(new PositiveNumberPipe())
// someMethod(@Body('amount') amount: number) { return amount; }
AReturns string '-5' without change
BReturns -5 as a number
CThrows BadRequestException with message 'Value must be a positive number'
DReturns 0 because negative values are reset
Attempts:
2 left
💡 Hint
Check the condition that triggers the exception in the transform method.

Practice

(1/5)
1. What is the main purpose of pipes in NestJS when handling input data?
easy
A. To style the user interface components
B. To manage database connections
C. To check and change input data before the app uses it
D. To handle HTTP responses only

Solution

  1. Step 1: Understand the role of pipes in NestJS

    Pipes are designed to process input data by validating and transforming it before it reaches the application logic.
  2. Step 2: Compare options with pipe functionality

    Only To check and change input data before the app uses it describes this behavior correctly; other options relate to unrelated tasks.
  3. Final Answer:

    To check and change input data before the app uses it -> Option C
  4. Quick Check:

    Pipes = Validate and transform input [OK]
Hint: Pipes act on input data before app logic runs [OK]
Common Mistakes:
  • Confusing pipes with UI styling tools
  • Thinking pipes manage database or HTTP responses only
  • Ignoring pipes' role in validation
2. Which of the following is the correct way to apply a built-in validation pipe in a NestJS controller method parameter?
easy
A. @Body(ValidationPipe) inputData: CreateDto
B. @Body(new ValidationPipe()) inputData: CreateDto
C. @Body() ValidationPipe inputData: CreateDto
D. @Body() inputData: ValidationPipe

Solution

  1. Step 1: Recall NestJS pipe syntax for method parameters

    To apply a pipe, you pass an instance of the pipe class inside the decorator, e.g., @Body(new ValidationPipe()).
  2. Step 2: Analyze each option's syntax

    @Body(new ValidationPipe()) inputData: CreateDto correctly instantiates and passes the ValidationPipe to @Body(). The other options either pass the class without instantiation, misplace the pipe, or confuse the order.
  3. Final Answer:

    @Body(new ValidationPipe()) inputData: CreateDto -> Option B
  4. Quick Check:

    Use new PipeClass() inside decorator [OK]
Hint: Use new PipeClass() inside decorator for pipes [OK]
Common Mistakes:
  • Instantiating pipe with new inside decorator
  • Placing pipe after parameter name
  • Confusing decorator and parameter order
3. Given this NestJS pipe that transforms input to a number:
import { PipeTransform, Injectable, ArgumentMetadata } from '@nestjs/common';

@Injectable()
export class ToNumberPipe implements PipeTransform {
  transform(value: any, metadata: ArgumentMetadata) {
    const val = Number(value);
    if (isNaN(val)) {
      throw new Error('Validation failed');
    }
    return val;
  }
}

What will be the output if the controller method receives the string '42' as input and uses this pipe?
medium
A. The number 42
B. The string '42'
C. An error is thrown
D. The value null

Solution

  1. Step 1: Understand the pipe's transform method

    The pipe converts the input value to a number using Number(value). If conversion fails, it throws an error.
  2. Step 2: Apply the pipe to input '42'

    Number('42') returns 42 (a number), which is valid, so no error is thrown and 42 is returned.
  3. Final Answer:

    The number 42 -> Option A
  4. Quick Check:

    String '42' converts to number 42 [OK]
Hint: Number('42') converts string to number without error [OK]
Common Mistakes:
  • Thinking the pipe returns the original string
  • Assuming an error is thrown for numeric strings
  • Confusing string and number types
4. Consider this NestJS pipe code snippet:
transform(value: any) {
  const num = parseInt(value);
  if (!num) {
    throw new Error('Invalid number');
  }
  return num;
}

What is the bug in this pipe when input is '0'?
medium
A. It throws an error incorrectly because !num is true for 0
B. It returns a string instead of a number
C. It does not parse the input at all
D. It always returns NaN

Solution

  1. Step 1: Analyze the condition !num with input '0'

    parseInt('0') returns 0, but !0 is true in JavaScript, so the error is thrown incorrectly.
  2. Step 2: Identify the bug cause

    The check should explicitly test for NaN, not falsy values, to avoid rejecting valid 0.
  3. Final Answer:

    It throws an error incorrectly because !num is true for 0 -> Option A
  4. Quick Check:

    Falsy check fails for 0, use isNaN instead [OK]
Hint: Falsy check fails for 0; use isNaN() to validate numbers [OK]
Common Mistakes:
  • Using !num to check invalid numbers
  • Ignoring 0 as a valid number
  • Not testing for NaN explicitly
5. You want to create a custom pipe in NestJS that validates an input string is a valid email and transforms it to lowercase. Which approach correctly combines validation and transformation?
hard
A. Validate email in controller, transform in pipe
B. Only transform to lowercase without validation
C. Throw error if value is lowercase already
D. In the transform method, first check email format with regex, then return value.toLowerCase()

Solution

  1. Step 1: Understand pipe responsibilities

    A pipe should both validate and transform input if needed, keeping logic together.
  2. Step 2: Evaluate options for combining validation and transformation

    In the transform method, first check email format with regex, then return value.toLowerCase() correctly validates email format and then transforms to lowercase inside the pipe. Transforming to lowercase only skips validation, separating validation and transformation across controller and pipe splits the logic, and throwing an error if already lowercase is illogical.
  3. Final Answer:

    In the transform method, first check email format with regex, then return value.toLowerCase() -> Option D
  4. Quick Check:

    Validate then transform inside pipe [OK]
Hint: Validate first, then transform input inside one pipe [OK]
Common Mistakes:
  • Separating validation and transformation outside pipe
  • Skipping validation step
  • Throwing errors for valid inputs
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