javascriptnode.jstypescriptnestjs

Can we have Multiple Interceptor for a single Http method in Nestjs?


Is it possible to have multiple interceptor for a single HTTP method. for instance we a have a file upload method, where the express fileInterceptor handles. And I have generalized response structure defined in a interceptor. so i wanted to use both of these interceptor for a single HTTP method.

Since I am new to Nestjs framework I am not familiar with the concept so wanted some insight on the same.


Solution

  • If you check out the Nest source code, you will be able to see that the decorator @UseInterceptors allows multiple interceptors:

    export function UseInterceptors(
      ...interceptors: (NestInterceptor | Function)[]
    ): MethodDecorator & ClassDecorator {
    //...
    

    You can use it like this:

    import { Controller, Post, UseInterceptors, UploadedFile, Body } from '@nestjs/common';
    import { FileInterceptor } from '@nestjs/platform-express';
    import { CustomResponseInterceptor } from './interceptors/custom-response.interceptor';
    
    @Controller('upload')
    export class UploadController {
      @Post()
      @UseInterceptors(
        FileInterceptor('file'),
        CustomResponseInterceptor
      )
      uploadFile(@UploadedFile() file: Express.Multer.File, @Body() body: any) {
        // Your logic to handle the file and request body
        return { file, body };
      }
    }