Bird
Raised Fist0
NestJSframework~20 mins

Custom pipes in NestJS - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
NestJS Pipes Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What is the output of this custom pipe transformation?
Consider this NestJS custom pipe that transforms input to uppercase. What will be the output when the pipe is applied to the string 'hello'?
NestJS
import { PipeTransform, Injectable, ArgumentMetadata } from '@nestjs/common';

@Injectable()
export class UppercasePipe implements PipeTransform {
  transform(value: any, metadata: ArgumentMetadata) {
    return typeof value === 'string' ? value.toUpperCase() : value;
  }
}

// Usage example:
// const result = new UppercasePipe().transform('hello', { type: 'body', metatype: String, data: '' });
A'HELLO'
B'hello'
Cundefined
DThrows TypeError
Attempts:
2 left
💡 Hint
Think about what the transform method does to string inputs.
📝 Syntax
intermediate
2:00remaining
Which option correctly implements a custom pipe that validates a positive integer?
You want to create a custom pipe that throws an error if the input is not a positive integer. Which code snippet correctly implements this?
A
import { PipeTransform, Injectable, BadRequestException } from '@nestjs/common';

@Injectable()
export class PositiveIntPipe implements PipeTransform {
  transform(value: any) {
    const val = parseFloat(value);
    if (!Number.isInteger(val) || val <= 0) {
      throw new BadRequestException('Value must be a positive integer');
    }
    return val;
  }
}
B
import { PipeTransform, Injectable } from '@nestjs/common';

@Injectable()
export class PositiveIntPipe implements PipeTransform {
  transform(value: any) {
    if (value <= 0) {
      throw new Error('Value must be positive');
    }
    return value;
  }
}
C
import { PipeTransform, Injectable, BadRequestException } from '@nestjs/common';

@Injectable()
export class PositiveIntPipe implements PipeTransform {
  transform(value: any) {
    const val = Number(value);
    if (val < 0) {
      throw new BadRequestException('Value must be positive');
    }
    return val;
  }
}
D
import { PipeTransform, Injectable, BadRequestException } from '@nestjs/common';

@Injectable()
export class PositiveIntPipe implements PipeTransform {
  transform(value: any) {
    const val = parseInt(value, 10);
    if (isNaN(val) || val <= 0) {
      throw new BadRequestException('Value must be a positive integer');
    }
    return val;
  }
}
Attempts:
2 left
💡 Hint
Check for integer parsing and proper error throwing.
🔧 Debug
advanced
2:00remaining
Why does this custom pipe cause a runtime error?
This pipe is intended to trim string inputs. Why does it cause a runtime error when a number is passed?
NestJS
import { PipeTransform, Injectable } from '@nestjs/common';

@Injectable()
export class TrimPipe implements PipeTransform {
  transform(value: any) {
    return value.trim();
  }
}
ABecause the transform method must return a Promise, but it returns a string.
BBecause 'value' might not be a string and numbers do not have a trim method, causing a TypeError.
CBecause the pipe is missing the @Injectable decorator, so it cannot be instantiated.
DBecause the pipe does not handle null values, causing a ReferenceError.
Attempts:
2 left
💡 Hint
Think about what happens when you call trim on a non-string.
❓ state_output
advanced
2:00remaining
What is the value returned by this custom pipe after transformation?
Given this pipe that parses JSON strings, what is the returned value when input is '{"a":1,"b":2}'?
NestJS
import { PipeTransform, Injectable, BadRequestException } from '@nestjs/common';

@Injectable()
export class ParseJsonPipe implements PipeTransform {
  transform(value: any) {
    try {
      return JSON.parse(value);
    } catch {
      throw new BadRequestException('Invalid JSON string');
    }
  }
}
A{'a': 1, 'b': 2}
B{a:1,b:2}
CThrows BadRequestException
D{"a":1,"b":2}
Attempts:
2 left
💡 Hint
Remember what JSON.parse returns.
🧠 Conceptual
expert
2:00remaining
Which statement about custom pipes in NestJS is true?
Select the correct statement about how custom pipes work in NestJS.
ACustom pipes can only be used for validation and cannot modify the input value.
BCustom pipes run after the controller method executes to modify the response.
CCustom pipes run before route handlers and can transform or validate incoming data.
DCustom pipes must always return a Promise and cannot return synchronous values.
Attempts:
2 left
💡 Hint
Think about when pipes are executed in the request lifecycle.

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