Bird
Raised Fist0
NestJSframework~20 mins

Response transformation in NestJS - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Response Transformer 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 interceptor?

Given the following NestJS interceptor that transforms the response by adding a status field, what will the client receive?

NestJS
import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common';
import { map } from 'rxjs/operators';
import { Observable } from 'rxjs';

@Injectable()
export class StatusInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    return next.handle().pipe(
      map(data => ({ status: 'success', data }))
    );
  }
}

// Controller method returns: { message: 'Hello' }
A{"data":{"message":"Hello"}}
B{"message":"Hello","status":"success"}
C{"status":"success","data":{"message":"Hello"}}
D{"status":"success"}
Attempts:
2 left
💡 Hint

Think about how the map operator wraps the original data.

📝 Syntax
intermediate
2:00remaining
Which option correctly applies a global response interceptor in NestJS?

Choose the correct way to apply a global interceptor that transforms all responses.

NestJS
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { TransformInterceptor } from './transform.interceptor';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  // Apply global interceptor here
  await app.listen(3000);
}
bootstrap();
Aapp.useGlobalInterceptors(new TransformInterceptor());
Bapp.useGlobalInterceptor(new TransformInterceptor());
Capp.useGlobalFilters(new TransformInterceptor());
Dapp.useInterceptor(new TransformInterceptor());
Attempts:
2 left
💡 Hint

Check the exact method name for applying global interceptors in NestJS.

🔧 Debug
advanced
2:00remaining
Why does this interceptor not transform the response?

Consider this interceptor code. Why does the client receive the original response without transformation?

NestJS
import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';

@Injectable()
export class NoTransformInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    return next.handle().pipe(
      map(data => ({ transformed: true, data }))
    );
  }
}
AThe interceptor should use tap instead of map to transform data.
BThe interceptor does not return the observable from next.handle(), so the pipeline is broken.
CThe map operator is not imported, so it causes a runtime error.
DThe interceptor must call next.handle() inside a try-catch block.
Attempts:
2 left
💡 Hint

Check if the observable is returned properly.

❓ state_output
advanced
2:00remaining
What is the final response after applying this interceptor and controller?

Given this controller and interceptor, what will the client receive?

NestJS
import { Controller, Get, UseInterceptors } from '@nestjs/common';
import { map } from 'rxjs/operators';

@Controller('test')
@UseInterceptors(class {
  intercept(context, next) {
    return next.handle().pipe(map(data => ({ modified: true, ...data })));
  }
})
export class TestController {
  @Get()
  getData() {
    return { message: 'Hi' };
  }
}
A{"modified":true,"message":"Hi"}
B{"message":"Hi","modified":true}
C{"message":"Hi"}
D{"modified":true,"data":{"message":"Hi"}}
Attempts:
2 left
💡 Hint

Remember how the spread operator works inside the map function.

🧠 Conceptual
expert
2:00remaining
Which statement about NestJS response transformation is TRUE?

Choose the correct statement about how response transformation works in NestJS.

AResponse transformation is only possible using middleware before the request reaches the controller.
BResponse transformation requires modifying the controller method's return type directly.
CGlobal filters are the recommended way to transform all responses in NestJS.
DInterceptors can modify the response stream by transforming the observable returned by the handler.
Attempts:
2 left
💡 Hint

Think about the role of interceptors versus filters and middleware.

Practice

(1/5)
1. What is the main purpose of response transformation in NestJS?
easy
A. To modify data before sending it to the client
B. To handle database connections
C. To manage user authentication
D. To log server errors

Solution

  1. Step 1: Understand response transformation concept

    Response transformation means changing the data before it is sent to the user.
  2. Step 2: Identify the correct purpose in NestJS context

    In NestJS, response transformation is used to modify or format the response data.
  3. Final Answer:

    To modify data before sending it to the client -> Option A
  4. Quick Check:

    Response transformation = modify data before sending [OK]
Hint: Response transformation changes output data before sending [OK]
Common Mistakes:
  • Confusing response transformation with authentication
  • Thinking it manages database connections
  • Assuming it logs errors
2. Which of the following is the correct way to apply a response transformation interceptor in NestJS?
easy
A. controller.transform(TransformInterceptor)
B. @UseInterceptors(new TransformInterceptor())
C. app.use(TransformInterceptor)
D. @Injectable(TransformInterceptor)

Solution

  1. Step 1: Recall NestJS interceptor usage

    Interceptors are applied using the @UseInterceptors decorator on controllers or methods.
  2. Step 2: Match correct syntax

    The correct syntax is @UseInterceptors(new InterceptorClass()).
  3. Final Answer:

    @UseInterceptors(new TransformInterceptor()) -> Option B
  4. Quick Check:

    Use @UseInterceptors with new instance [OK]
Hint: Use @UseInterceptors with new interceptor instance [OK]
Common Mistakes:
  • Using @Injectable instead of @UseInterceptors
  • Calling interceptor as a method on controller
  • Trying to use app.use for interceptors
3. Given this interceptor code snippet, what will be the transformed response?
intercept(context, next) {
  return next.handle().pipe(map(data => ({ result: data }))); 
}
medium
A. { data: originalData }
B. originalData
C. { result: originalData }
D. An error will occur

Solution

  1. Step 1: Understand the interceptor's map function

    The map operator wraps the original data inside an object with key 'result'.
  2. Step 2: Predict the transformed output

    The response will be an object: { result: originalData }.
  3. Final Answer:

    { result: originalData } -> Option C
  4. Quick Check:

    map wraps data in { result: ... } [OK]
Hint: map operator wraps data in new object key [OK]
Common Mistakes:
  • Assuming original data is unchanged
  • Confusing key name as 'data' instead of 'result'
  • Expecting an error from this code
4. What is wrong with this interceptor code that tries to transform the response?
intercept(context, next) {
  next.handle().pipe(map(data => data.trim()));
}
medium
A. next.handle() should not be called
B. map operator cannot be used inside intercept
C. trim() is not a valid method on data
D. Missing return statement for the observable

Solution

  1. Step 1: Check interceptor return value

    Interceptors must return the observable from next.handle().pipe(...).
  2. Step 2: Identify missing return

    The code calls next.handle().pipe(...) but does not return it, so the response is undefined.
  3. Final Answer:

    Missing return statement for the observable -> Option D
  4. Quick Check:

    Always return next.handle().pipe(...) [OK]
Hint: Always return the observable from intercept method [OK]
Common Mistakes:
  • Forgetting to return the observable
  • Assuming map cannot be used in intercept
  • Misusing trim() on non-string data
5. You want to hide the user's password field from all API responses using response transformation. Which approach is best in NestJS?
hard
A. Create an interceptor that maps the response and deletes the password field
B. Modify the database schema to exclude password
C. Use a middleware to filter out password from requests
D. Send password as null in the controller methods

Solution

  1. Step 1: Understand response transformation goal

    We want to remove sensitive info from outgoing responses, not database or requests.
  2. Step 2: Choose best NestJS method

    Interceptors can transform responses globally, ideal for removing password fields before sending.
  3. Step 3: Evaluate other options

    Modifying DB schema or middleware won't affect response data; setting password null in controllers is repetitive.
  4. Final Answer:

    Create an interceptor that maps the response and deletes the password field -> Option A
  5. Quick Check:

    Use interceptor to hide sensitive response data [OK]
Hint: Use interceptor to remove sensitive fields from responses [OK]
Common Mistakes:
  • Trying to filter password in middleware (affects requests)
  • Changing database schema instead of response
  • Manually nulling password in every controller
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