All files / core/helpers external-context-creator.ts

96.51% Statements 83/86
84.62% Branches 22/26
95.83% Functions 23/24
96.34% Lines 79/82
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 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 2211x 1x   1x 1x 1x 1x       1x 1x 1x 1x 1x                         1x 60x     60x 60x 60x 60x 60x 60x 60x       42x                                   4x 4x 4x       4x 4x             4x         4x 4x 4x       4x     4x   4x 1x       1x     4x 2x 2x           2x 1x   1x             1x         7x 7x 2x   5x 1x 1x     4x       2x 2x 1x   2x                 1x 1x 3x 3x     3x   3x 1x 1x 1x   2x 2x     2x         3x 1x 1x             6x 1x 1x               1x 1x   1x               6x               2x               4x 1x   3x      
import { ForbiddenException, ParamData } from '@nestjs/common';
import { CUSTOM_ROUTE_AGRS_METADATA } from '@nestjs/common/constants';
import { Controller, Transform } from '@nestjs/common/interfaces';
import { isFunction, isUndefined } from '@nestjs/common/utils/shared.utils';
import { FORBIDDEN_MESSAGE } from '../guards/constants';
import { GuardsConsumer } from '../guards/guards-consumer';
import { GuardsContextCreator } from '../guards/guards-context-creator';
import { NestContainer } from '../injector/container';
import { Module } from '../injector/module';
import { ModulesContainer } from '../injector/modules-container';
import { InterceptorsConsumer } from '../interceptors/interceptors-consumer';
import { InterceptorsContextCreator } from '../interceptors/interceptors-context-creator';
import { PipesConsumer } from '../pipes/pipes-consumer';
import { PipesContextCreator } from '../pipes/pipes-context-creator';
import { ContextUtils, ParamProperties } from './context-utils';
 
export interface ParamsMetadata {
  [prop: number]: {
    index: number;
    data?: ParamData;
  };
}
 
export interface ParamsFactory {
  exchangeKeyForValue(type: number, data: ParamData, args: any): any;
}
 
export class ExternalContextCreator {
  private readonly contextUtils = new ContextUtils();
 
  constructor(
    private readonly guardsContextCreator: GuardsContextCreator,
    private readonly guardsConsumer: GuardsConsumer,
    private readonly interceptorsContextCreator: InterceptorsContextCreator,
    private readonly interceptorsConsumer: InterceptorsConsumer,
    private readonly modulesContainer: ModulesContainer,
    private readonly pipesContextCreator: PipesContextCreator,
    private readonly pipesConsumer: PipesConsumer,
  ) {}
 
  static fromContainer(container: NestContainer): ExternalContextCreator {
    return new ExternalContextCreator(
      new GuardsContextCreator(container, container.applicationConfig),
      new GuardsConsumer(),
      new InterceptorsContextCreator(container, container.applicationConfig),
      new InterceptorsConsumer(),
      container.getModules(),
      new PipesContextCreator(container, container.applicationConfig),
      new PipesConsumer(),
    );
  }
 
  public create<T extends ParamsMetadata = ParamsMetadata>(
    instance: Controller,
    callback: (...args) => any,
    methodName: string,
    metadataKey?: string,
    paramsFactory?: ParamsFactory,
  ) {
    const module = this.findContextModuleName(instance.constructor);
    const pipes = this.pipesContextCreator.create(instance, callback, module);
    const paramtypes = this.contextUtils.reflectCallbackParamtypes(
      instance,
      methodName,
    );
    const guards = this.guardsContextCreator.create(instance, callback, module);
    const interceptors = this.interceptorsContextCreator.create(
      instance,
      callback,
      module,
    );
 
    const metadata =
      this.contextUtils.reflectCallbackMetadata<T>(
        instance,
        methodName,
        metadataKey || '',
      ) || {};
    const keys = Object.keys(metadata);
    const argsLength = this.contextUtils.getArgumentsLength(keys, metadata);
    const paramsMetadata = paramsFactory
      ? this.exchangeKeysForValues(keys, metadata, module, paramsFactory)
      : null;
 
    const paramsOptions = paramsMetadata
      ? this.contextUtils.mergeParamsMetatypes(paramsMetadata, paramtypes)
      : [];
    const fnApplyPipes = this.createPipesFn(pipes, paramsOptions);
 
    const handler = (initialArgs, ...args) => async () => {
      Iif (fnApplyPipes) {
        await fnApplyPipes(initialArgs, ...args);
        return callback.apply(instance, initialArgs);
      }
      return callback.apply(instance, args);
    };
 
    return async (...args) => {
      const initialArgs = this.contextUtils.createNullArray(argsLength);
      const canActivate = await this.guardsConsumer.tryActivate(
        guards,
        args,
        instance,
        callback,
      );
      if (!canActivate) {
        throw new ForbiddenException(FORBIDDEN_MESSAGE);
      }
      const result = await this.interceptorsConsumer.intercept(
        interceptors,
        args,
        instance,
        callback,
        handler(initialArgs, ...args),
      );
      return this.transformToResult(result);
    };
  }
 
  public findContextModuleName(constructor: Function): string {
    const className = constructor.name;
    if (!className) {
      return '';
    }
    for (const [key, module] of [...this.modulesContainer.entries()]) {
      Eif (this.findComponentByClassName(module, className)) {
        return key;
      }
    }
    return '';
  }
 
  public findComponentByClassName(module: Module, className: string): boolean {
    const { components } = module;
    const hasComponent = [...components.keys()].some(
      component => component === className,
    );
    return hasComponent;
  }
 
  public exchangeKeysForValues<TMetadata = any>(
    keys: string[],
    metadata: TMetadata,
    moduleContext: string,
    paramsFactory: ParamsFactory,
  ): ParamProperties[] {
    this.pipesContextCreator.setModuleContext(moduleContext);
    return keys.map(key => {
      const { index, data, pipes: pipesCollection } = metadata[key];
      const pipes = this.pipesContextCreator.createConcreteContext(
        pipesCollection,
      );
      const type = this.contextUtils.mapParamType(key);
 
      if (key.includes(CUSTOM_ROUTE_AGRS_METADATA)) {
        const { factory } = metadata[key];
        const customExtractValue = this.getCustomFactory(factory, data);
        return { index, extractValue: customExtractValue, type, data, pipes };
      }
      const numericType = Number(type);
      const extractValue = (...args) =>
        paramsFactory.exchangeKeyForValue(numericType, data, args);
 
      return { index, extractValue, type: numericType, data, pipes };
    });
  }
 
  public getCustomFactory(factory: (...args) => void, data): (...args) => any {
    return isFunction(factory)
      ? (...args) => factory(data, args)
      : () => null;
  }
 
  public createPipesFn(
    pipes: any[],
    paramsOptions: (ParamProperties & { metatype?: any })[],
  ) {
    const pipesFn = async (args, ...gqlArgs) => {
      await Promise.all(
        paramsOptions.map(async param => {
          const {
            index,
            extractValue,
            type,
            data,
            metatype,
            pipes: paramPipes,
          } = param;
          const value = extractValue(...gqlArgs);
 
          args[index] = await this.getParamValue(
            value,
            { metatype, type, data },
            pipes.concat(paramPipes),
          );
        }),
      );
    };
    return paramsOptions.length ? pipesFn : null;
  }
 
  public async getParamValue<T>(
    value: T,
    { metatype, type, data },
    transforms: Transform<any>[],
  ): Promise<any> {
    return this.pipesConsumer.apply(
      value,
      { metatype, type, data },
      transforms,
    );
  }
 
  public async transformToResult(resultOrDeffered) {
    if (resultOrDeffered && isFunction(resultOrDeffered.subscribe)) {
      return resultOrDeffered.toPromise();
    }
    return resultOrDeffered;
  }
}