In NestJS, Interceptors are a powerful feature that enables additional processing, transformation, or extension of requests and responses. They can be invoked at different stages of the request processing pipeline, allowing you to execute logic before or after method execution.
To modify the content of PUT requests and responses using interceptors, you must first create an interceptor class. This class must implement the NestInterceptor interface and define an intercept method. Within this method, you can access the request object (ExecutionContext) and modify it, or manipulate the response obtained after the handler method is called.
Here is an example demonstrating how to create a simple interceptor to modify the request body and response body of PUT requests:
typescriptimport { Injectable, NestInterceptor, ExecutionContext, CallHandler, } from '@nestjs/common'; import { Observable } from 'rxjs'; import { map } from 'rxjs/operators'; @Injectable() export class PutRequestInterceptor implements NestInterceptor { intercept(context: ExecutionContext, next: CallHandler): Observable<any> { const ctx = context.switchToHttp(); const request = ctx.getRequest(); // Modify the PUT request body if (request.method === 'PUT') { const body = request.body; // Assume we want to add a `timestamp` field to the request body request.body = { ...body, timestamp: new Date().toISOString() }; } // Use RxJS map operator to modify the response body return next.handle().pipe( map(data => { // Assume we want to add a `success` field to the response body return { ...data, success: true }; }), ); } }
Next, apply this interceptor to the corresponding PUT route handler. This can be achieved by applying the @UseInterceptors decorator to the controller method:
typescriptimport { Controller, Put, UseInterceptors } from '@nestjs/common'; @Controller('items') export class ItemsController { @Put() @UseInterceptors(PutRequestInterceptor) updateItem() { // Handle PUT request and return response } }
In this example, we first check the request method. If it is a PUT request, we modify the request body by adding a timestamp field. Subsequently, we use the RxJS map operator to modify the response from the handler method by adding a success field.
Note that interceptors can be used for various purposes, including logging, exception mapping, and request-response transformation. By combining multiple interceptors, you can build powerful and flexible middleware pipelines. In practice, your interceptors can handle complex data processing and business logic as needed.