Use Interceptor inside another Interceptor In nestjs

3.4k Views Asked by At

I am creating a interceptor Inside that I want to use FileInterceptor but I am getting error Declaration Expected after FileInterceptor

import { CallHandler, ExecutionContext, Injectable, NestInterceptor, UseInterceptors } from '@nestjs/common';
import { Observable } from 'rxjs';
import { FileInterceptor } from '@nestjs/platform-express';
import { diskStorage } from 'multer';
import { extname } from 'path';

@Injectable()
export class UploaderInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {

    @UseInterceptors(FileInterceptor('file', {
      storage: diskStorage({
          destination: './uploads'
          , filename: (req, file, cb) => {
              // Generating a 32 random chars long string
              const randomName = Array(32).fill(null).map(() => (Math.round(Math.random() * 16)).toString(16)).join('')
              //Calling the callback passing the random name generated with the original extension name
              cb(null, `${randomName}${extname(file.originalname)}`)
          }
      })
  }));


    return next.handle();
  }
}
1

There are 1 best solutions below

2
On

FileInterceptor is a mixin meaning it is a function that returns a class. This function takes in a configuration for the interceptor to actually use. What you can do instead of trying to make a class that makes use of the interceptor under the hood or extends it, is essentially make an alias for the configuration like so:

export const UploadInterceptor = FileInterceptor('file', {
  storage: diskStorage({
      destination: './uploads',
      filename: (req, file, cb) => {
        // Generating a 32 random characters long string
        const randomName = Array(32).fill(null).map(() => (Math.round(Math.random() * 16)).toString(16)).join('')
        //Calling the callback passing the random name generated with the original extension name
        cb(null, `${randomName}${extname(file.originalname)}`)
      }
  })
})

Now with this exported constant (that is actually a class), you can then make use of the interceptor as such:

@Controller('upload')
export class UploadController {

  @UseInterceptors(UploadInterceptor)
  @Post()
  uploadFile() {
  // do logic;
  }
}

And everything should work out for you.