# All files / common/files/interceptors files.interceptor.ts

100% Statements 19/19
100% Branches 3/3
100% Functions 5/5
100% Lines 18/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
    581x

    1x
    1x

    1x

    1x

    1x

    3x

    2x

    2x

    2x
    2x

    2x
    1x
    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 { 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 FilesInterceptor(
      fieldName: string,
      maxCount?: number,
      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.array(fieldName, maxCount)(
              ctx.getRequest(),
              ctx.getResponse(),
              err => {
                if (err) {
                  const error = transformException(err);
                  return reject(error);
                }
                resolve();
              },
            ),
          );
          return call$;
        }
      }
      const Interceptor = mixin(MixinInterceptor);
      return Interceptor;
    }