Bird
Raised Fist0
NestJSframework~10 mins

Custom pipes in NestJS - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Custom pipes
Request received
↓
Pipe invoked
↓
Transform or Validate input
↓
Valid
↓
Pass to
↓
Controller
When a request comes in, NestJS runs the custom pipe to check or change data before the controller uses it.
Execution Sample
NestJS
import { PipeTransform, Injectable, ArgumentMetadata, BadRequestException } from '@nestjs/common';

@Injectable()
export class ParseIntPipe implements PipeTransform {
  transform(value: any, metadata: ArgumentMetadata) {
    const val = parseInt(value, 10);
    if (isNaN(val)) {
      throw new BadRequestException('Validation failed');
    }
    return val;
  }
}
This pipe tries to convert input to an integer and throws an error if it fails.
Execution Table
StepInput ValueActionResultNext Step
1"123"parseInt("123")123 (number)Pass to controller
2"abc"parseInt("abc")NaNThrow BadRequestException
3nullparseInt(null)0Pass to controller
4"42abc"parseInt("42abc")42 (number)Pass to controller
💡 Execution stops when input is valid and passed or invalid and error thrown.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3After Step 4
valueundefined"123""abc"null"42abc"
valundefined123NaN042
Key Moments - 3 Insights
Why does parseInt("42abc") return 42 and not NaN?
parseInt reads numbers from the start of the string until it hits a non-digit. So "42abc" becomes 42. See execution_table row 4.
What happens if the pipe throws an error?
The request stops and NestJS sends a 400 Bad Request response. This is shown in execution_table rows 2.
Why do we return the parsed value instead of the original?
Returning the parsed value ensures the controller gets the correct data type. See execution_table row 1 where "123" becomes 123.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the result of parsing "abc" at step 2?
ANaN
B123
Cabc
D42
💡 Hint
Check the 'Result' column in execution_table row 2.
At which step does the pipe pass the value to the controller without error?
AStep 2
BStep 1
CStep 3
DStep 4
💡 Hint
Look for 'Pass to controller' in the 'Next Step' column.
If the input was "100xyz", what would the pipe return?
ANaN
B100
C"100xyz"
DThrow error
💡 Hint
Refer to how parseInt handles strings with numbers followed by letters, like in step 4.
Concept Snapshot
Custom pipes in NestJS transform or validate data before it reaches controllers.
They implement PipeTransform with a transform() method.
If validation fails, throw an exception to stop the request.
Return the transformed value to pass it on.
Useful for type conversion and input checks.
Full Transcript
Custom pipes in NestJS run when a request comes in. They check or change the input data before the controller uses it. For example, a pipe can convert a string to a number. If the input is not valid, the pipe throws an error and stops the request. Otherwise, it returns the new value. This helps keep controllers clean and safe. The example pipe tries to parse an integer. If parsing fails, it throws a BadRequestException. If it succeeds, it passes the number to the controller. This process is shown step-by-step in the execution table and variable tracker.

Practice

(1/5)
1.

What is the main purpose of a custom pipe in NestJS?

easy
A. To transform or validate data before it reaches the route handler
B. To handle database connections automatically
C. To manage user sessions and cookies
D. To style the frontend components

Solution

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

    Pipes are used to transform or validate incoming data before it reaches the controller methods.
  2. Step 2: Identify what custom pipes specifically do

    Custom pipes allow developers to create their own logic for data transformation or validation to ensure data safety and correctness.
  3. Final Answer:

    To transform or validate data before it reaches the route handler -> Option A
  4. Quick Check:

    Custom pipes = data validation/transformation [OK]
Hint: Pipes act on data before controller uses it [OK]
Common Mistakes:
  • Confusing pipes with middleware
  • Thinking pipes handle database or session logic
  • Assuming pipes style frontend components
2.

Which of the following is the correct way to define a custom pipe class in NestJS?

export class MyPipe implements PipeTransform {
  transform(value: any, metadata: ArgumentMetadata) {
    // logic here
  }
}
easy
A. export class MyPipe implements PipeTransform { transform(value: any) { } }
B. export class MyPipe implements PipeTransform { transform(value: any, metadata: ArgumentMetadata) { } }
C. export function MyPipe(value: any) { return value; }
D. export class MyPipe { transform(value: any, metadata: ArgumentMetadata) { } }

Solution

  1. Step 1: Recall the PipeTransform interface signature

    The transform method must accept two parameters: value and metadata of type ArgumentMetadata.
  2. Step 2: Check which option matches the correct method signature

    export class MyPipe implements PipeTransform { transform(value: any, metadata: ArgumentMetadata) { } } correctly implements the transform method with both parameters and the class implements PipeTransform.
  3. Final Answer:

    export class MyPipe implements PipeTransform { transform(value: any, metadata: ArgumentMetadata) { } } -> Option B
  4. Quick Check:

    transform(value, metadata) = correct signature [OK]
Hint: transform method needs value and metadata parameters [OK]
Common Mistakes:
  • Omitting the metadata parameter
  • Using a function instead of a class
  • Not implementing PipeTransform interface
3.

Given this custom pipe code, what will be the output if the input value is "123"?

import { PipeTransform, Injectable, BadRequestException } from '@nestjs/common';

@Injectable()
export class ParseIntPipe implements PipeTransform {
  transform(value: any) {
    const val = parseInt(value, 10);
    if (isNaN(val)) {
      throw new BadRequestException('Validation failed');
    }
    return val;
  }
}

Input: "123"

medium
A. Returns NaN
B. Throws BadRequestException
C. Returns string "123"
D. Returns number 123

Solution

  1. Step 1: Understand parseInt behavior on string "123"

    parseInt("123", 10) converts the string "123" to the number 123.
  2. Step 2: Check the validation condition

    Since 123 is a valid number, isNaN(val) is false, so no exception is thrown and the number 123 is returned.
  3. Final Answer:

    Returns number 123 -> Option D
  4. Quick Check:

    parseInt("123") = 123 [OK]
Hint: parseInt("123") returns number 123, no error [OK]
Common Mistakes:
  • Thinking it returns string instead of number
  • Assuming it throws error for numeric strings
  • Confusing NaN with valid number
4.

Identify the error in this custom pipe code:

import { PipeTransform, Injectable } from '@nestjs/common';

@Injectable()
export class UppercasePipe implements PipeTransform {
  transform(value: string) {
    return value.toUpperCase;
  }
}
medium
A. Missing @Injectable decorator
B. transform method missing return type
C. toUpperCase is used without parentheses
D. PipeTransform interface not implemented

Solution

  1. Step 1: Check the transform method implementation

    The method returns value.toUpperCase without parentheses, which is a reference to the function, not the result.
  2. Step 2: Identify correct usage of toUpperCase

    toUpperCase is a method and must be called with parentheses: value.toUpperCase()
  3. Final Answer:

    toUpperCase is used without parentheses -> Option C
  4. Quick Check:

    Method calls need () to execute [OK]
Hint: Remember to call string methods with () [OK]
Common Mistakes:
  • Forgetting parentheses on method calls
  • Assuming decorators are missing when present
  • Ignoring interface implementation
5.

You want to create a custom pipe that trims whitespace and converts input to lowercase. Which of these implementations correctly achieves this?

import { PipeTransform, Injectable } from '@nestjs/common';

@Injectable()
export class NormalizePipe implements PipeTransform {
  transform(value: any) {
    // Which option is correct?
  }
}
hard
A. return value.trim().toLowerCase();
B. return value.replace(/\s/g, '').toLowerCase();
C. return value.trim.toLowerCase();
D. return value.toLowerCase.trim();

Solution

  1. Step 1: Understand method chaining order

    trim() removes whitespace from start and end, then toLowerCase() converts to lowercase. The order matters to avoid errors.
  2. Step 2: Check method call syntax

    Both trim() and toLowerCase() are methods and must be called with parentheses. return value.trim().toLowerCase(); correctly calls them in order: value.trim().toLowerCase()
  3. Final Answer:

    return value.trim().toLowerCase(); -> Option A
  4. Quick Check:

    Correct method chaining with () = return value.trim().toLowerCase(); [OK]
Hint: Call trim() before toLowerCase(), both with () [OK]
Common Mistakes:
  • Calling methods without parentheses
  • Wrong method chaining order
  • Using properties instead of methods
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