Bird
Raised Fist0
NestJSframework~10 mins

Why pipes transform and validate input in NestJS - Visual Breakdown

Choose your learning style10 modes available
Concept Flow - Why pipes transform and validate input
Request Received
↓
Input Data
↓
Pipe: Validate Input
↓
Pipe: Transform Input
↓
Controller Receives Clean Data
↓
Process Request
Input data flows through pipes that first check if data is valid, then transform it before the controller uses it.
Execution Sample
NestJS
async function handleRequest(input) {
  const validInput = validate(input);
  if (!validInput) throw new Error('Invalid input');
  const transformed = transform(input);
  return process(transformed);
}
This code validates input, throws error if invalid, transforms valid input, then processes it.
Execution Table
StepActionInputValidation ResultTransformation ResultNext Step
1Receive input{ age: '25' }Not checked yetNot transformed yetValidate input
2Validate input{ age: '25' }Valid (age is string but numeric)Not transformed yetTransform input
3Transform input{ age: '25' }Valid{ age: 25 } (string to number)Send to controller
4Controller receives{ age: 25 }Valid{ age: 25 }Process request
5Process request{ age: 25 }Valid{ age: 25 }Request completed
6Receive input{ age: 'abc' }Not checked yetNot transformed yetValidate input
7Validate input{ age: 'abc' }Invalid (age not numeric)Not transformedThrow error
8Throw errorError: Invalid input--Request stopped
💡 Execution stops when validation fails or after processing valid input.
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 4Final
input{ age: '25' }{ age: '25' }{ age: '25' }{ age: 25 }{ age: 25 }
validationResultNot checkedValidValidValidValid
transformedInputNot transformedNot transformed{ age: 25 }{ age: 25 }{ age: 25 }
errornullnullnullnullnull
Key Moments - 3 Insights
Why do pipes validate input before transforming it?
Validation ensures the data is correct and safe before any changes. See execution_table step 2 where invalid input stops the process before transformation.
What happens if input is invalid during validation?
The pipe throws an error and stops further processing, as shown in execution_table step 7 and 8.
Why transform input after validation?
Transformation converts input into the format the controller expects, like string to number in step 3, so the controller works with clean data.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the transformation result at step 3?
AError: Invalid input
B{ age: 25 } (string to number)
C{ age: '25' } (unchanged)
DNot transformed yet
💡 Hint
Check the 'Transformation Result' column at step 3 in execution_table.
At which step does the process stop for invalid input?
AStep 7
BStep 5
CStep 3
DStep 2
💡 Hint
Look for 'Throw error' action in execution_table.
If input was already a number, how would the transformation step change?
AValidation would fail
BTransformation would convert number to string
CTransformation would be skipped or keep input as is
DController would reject input
💡 Hint
Refer to variable_tracker for how transformedInput changes after step 3.
Concept Snapshot
Pipes in NestJS first validate input to ensure it is correct.
If invalid, they stop processing and throw an error.
If valid, pipes transform input into the needed format.
This clean data is then passed to controllers.
This keeps app safe and data consistent.
Full Transcript
When a request comes in, NestJS pipes first check if the input data is valid. If the data is invalid, the pipe throws an error and stops the request. If the data is valid, the pipe transforms the input, for example changing strings to numbers. Then the controller receives this clean, transformed data to process the request. This flow ensures the app only works with safe and correct data.

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