All files / common/files/interceptors file-fields.interceptor.ts

89.47% Statements 17/19
66.67% Branches 2/3
100% Functions 5/5
88.89% Lines 16/18
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 601x   1x 1x             1x   1x       1x       3x               2x                   2x   2x 2x       1x       1x       1x     3x 3x    
import * as multer from 'multer';
import { Observable } from 'rxjs';
import { Inject, Optional } from '../../decorators';
import { mixin } from '../../decorators/core/component.decorator';
import { ExecutionContext } from '../../interfaces';
import {
  MulterField,
  MulterOptions,
} from '../../interfaces/external/multer-options.interface';
import { NestInterceptor } from '../../interfaces/features/nest-interceptor.interface';
import { MULTER_MODULE_OPTIONS } from '../files.constants';
import { MulterModuleOptions } from '../interfaces';
import { transformException } from '../multer/multer.utils';
 
type MulterInstance = any;
 
export function FileFieldsInterceptor(
  uploadFields: MulterField[],
  localOptions?: MulterOptions,
) {
  class MixinInterceptor implements NestInterceptor {
    protected multer: MulterInstance;
 
    constructor(
      @Optional()
      @Inject(MULTER_MODULE_OPTIONS)
      options: MulterModuleOptions = {},
    ) {
      this.multer = multer({
        ...options,
        ...localOptions,
      });
    }
 
    async intercept(
      context: ExecutionContext,
      call$: Observable<any>,
    ): Promise<Observable<any>> {
      const ctx = context.switchToHttp();
 
      await new Promise((resolve, reject) =>
        this.multer.fields(uploadFields)(
          ctx.getRequest(),
          ctx.getResponse(),
          err => {
            Iif (err) {
              const error = transformException(err);
              return reject(error);
            }
            resolve();
          },
        ),
      );
      return call$;
    }
  }
  const Interceptor = mixin(MixinInterceptor);
  return Interceptor;
}