All files / core/injector module.ts

92.31% Statements 108/117
77.08% Branches 37/48
95.45% Functions 42/44
92.31% Lines 108/117
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 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378              1x 1x             1x 1x 1x 1x 1x 1x   1x 1x 1x                                     1x   45x 45x 45x 45x 45x     45x 45x 45x   45x 45x               3x       1x       44x       2x       2x       1x       2x 1x   1x 1x       11x       45x 45x 45x 45x 45x 45x 45x       45x 45x                 45x                 45x                 45x                     45x                 45x                 45x                 3x 1x   2x                 7x 1x   6x           6x           13x             4x 4x 4x       4x 1x 3x 1x 2x 1x   4x       4x       3x       2x       1x       1x 1x                 1x 1x                           1x 1x                         3x 1x   3x 2x 1x   1x       1x           2x 2x 2x           4x 2x   2x 2x 1x 1x 1x 1x   2x 1x 1x   1x       5x                 3x       2x 1x   1x             47x 47x   47x             1x     1x                              
import {
  Controller,
  DynamicModule,
  Injectable,
  NestModule,
} from '@nestjs/common/interfaces';
import { Type } from '@nestjs/common/interfaces/type.interface';
import { randomStringGenerator } from '@nestjs/common/utils/random-string-generator.util';
import {
  isFunction,
  isNil,
  isString,
  isSymbol,
  isUndefined,
} from '@nestjs/common/utils/shared.utils';
import { InvalidClassException } from '../errors/exceptions/invalid-class.exception';
import { RuntimeException } from '../errors/exceptions/runtime.exception';
import { UnknownExportException } from '../errors/exceptions/unknown-export.exception';
import { ApplicationReferenceHost } from '../helpers/application-ref-host';
import { ExternalContextCreator } from '../helpers/external-context-creator';
import { Reflector } from '../services/reflector.service';
import { InstanceWrapper, NestContainer } from './container';
import { ModuleRef } from './module-ref';
import { ModulesContainer } from './modules-container';
import { HTTP_SERVER_REF } from './tokens';
 
export interface CustomComponent {
  provide: any;
  name: string;
}
export type OpaqueToken = string | symbol | object | Type<any>;
export type CustomClass = CustomComponent & { useClass: Type<any> };
export type CustomFactory = CustomComponent & {
  useFactory: (...args) => any;
  inject?: OpaqueToken[];
};
export type CustomValue = CustomComponent & { useValue: any };
export type ComponentMetatype =
  | Type<Injectable>
  | CustomFactory
  | CustomValue
  | CustomClass;
 
export class Module {
  private readonly _id: string;
  private readonly _relatedModules = new Set<Module>();
  private readonly _components = new Map<any, InstanceWrapper<Injectable>>();
  private readonly _injectables = new Map<any, InstanceWrapper<Injectable>>();
  private readonly _routes = new Map<string, InstanceWrapper<Controller>>();
  private readonly _exports = new Set<string | symbol>();
 
  constructor(
    private readonly _metatype: Type<any>,
    private readonly _scope: Type<any>[],
    private readonly container: NestContainer,
  ) {
    this.addCoreInjectables(container);
    this._id = randomStringGenerator();
  }
 
  get id(): string {
    return this._id;
  }
 
  get scope(): Type<any>[] {
    return this._scope;
  }
 
  get relatedModules(): Set<Module> {
    return this._relatedModules;
  }
 
  get components(): Map<string, InstanceWrapper<Injectable>> {
    return this._components;
  }
 
  get injectables(): Map<string, InstanceWrapper<Injectable>> {
    return this._injectables;
  }
 
  get routes(): Map<string, InstanceWrapper<Controller>> {
    return this._routes;
  }
 
  get exports(): Set<string | symbol> {
    return this._exports;
  }
 
  get instance(): NestModule {
    if (!this._components.has(this._metatype.name)) {
      throw new RuntimeException();
    }
    const module = this._components.get(this._metatype.name);
    return module.instance as NestModule;
  }
 
  get metatype(): Type<any> {
    return this._metatype;
  }
 
  public addCoreInjectables(container: NestContainer) {
    this.addModuleAsComponent();
    this.addModuleRef();
    this.addReflector(container.getReflector());
    this.addApplicationRef(container.getApplicationRef());
    this.addExternalContextCreator(container.getExternalContextCreator());
    this.addModulesContainer(container.getModulesContainer());
    this.addApplicationRefHost(container.getApplicationRefHost());
  }
 
  public addModuleRef() {
    const moduleRef = this.createModuleRefMetatype();
    this._components.set(ModuleRef.name, {
      name: ModuleRef.name,
      metatype: ModuleRef as any,
      isResolved: true,
      instance: new moduleRef(),
    });
  }
 
  public addModuleAsComponent() {
    this._components.set(this._metatype.name, {
      name: this._metatype.name,
      metatype: this._metatype,
      isResolved: false,
      instance: null,
    });
  }
 
  public addReflector(reflector: Reflector) {
    this._components.set(Reflector.name, {
      name: Reflector.name,
      metatype: Reflector,
      isResolved: true,
      instance: reflector,
    });
  }
 
  public addApplicationRef(applicationRef: any) {
    this._components.set(HTTP_SERVER_REF, {
      name: HTTP_SERVER_REF,
      metatype: {} as any,
      isResolved: true,
      instance: applicationRef || {},
    });
  }
 
  public addExternalContextCreator(
    externalContextCreator: ExternalContextCreator,
  ) {
    this._components.set(ExternalContextCreator.name, {
      name: ExternalContextCreator.name,
      metatype: ExternalContextCreator,
      isResolved: true,
      instance: externalContextCreator,
    });
  }
 
  public addModulesContainer(modulesContainer: ModulesContainer) {
    this._components.set(ModulesContainer.name, {
      name: ModulesContainer.name,
      metatype: ModulesContainer,
      isResolved: true,
      instance: modulesContainer,
    });
  }
 
  public addApplicationRefHost(applicationRefHost: ApplicationReferenceHost) {
    this._components.set(ApplicationReferenceHost.name, {
      name: ApplicationReferenceHost.name,
      metatype: ApplicationReferenceHost,
      isResolved: true,
      instance: applicationRefHost,
    });
  }
 
  public addInjectable(injectable: Type<Injectable>) {
    if (this.isCustomProvider(injectable)) {
      return this.addCustomProvider(injectable, this._injectables);
    }
    this._injectables.set(injectable.name, {
      name: injectable.name,
      metatype: injectable,
      instance: null,
      isResolved: false,
    });
  }
 
  public addComponent(component: ComponentMetatype): string {
    if (this.isCustomProvider(component)) {
      return this.addCustomProvider(component, this._components);
    }
    this._components.set((component as Type<Injectable>).name, {
      name: (component as Type<Injectable>).name,
      metatype: component as Type<Injectable>,
      instance: null,
      isResolved: false,
    });
    return (component as Type<Injectable>).name;
  }
 
  public isCustomProvider(
    component: ComponentMetatype,
  ): component is CustomClass | CustomFactory | CustomValue {
    return !isNil((component as CustomComponent).provide);
  }
 
  public addCustomProvider(
    component: CustomFactory | CustomValue | CustomClass,
    collection: Map<string, any>,
  ): string {
    const { provide } = component;
    const name = isFunction(provide) ? provide.name : provide;
    const componentWithName = {
      ...component,
      name,
    };
    if (this.isCustomClass(componentWithName))
      this.addCustomClass(componentWithName, collection);
    else if (this.isCustomValue(componentWithName))
      this.addCustomValue(componentWithName, collection);
    else if (this.isCustomFactory(componentWithName))
      this.addCustomFactory(componentWithName, collection);
 
    return name;
  }
 
  public isCustomClass(component): component is CustomClass {
    return !isUndefined((component as CustomClass).useClass);
  }
 
  public isCustomValue(component): component is CustomValue {
    return !isUndefined((component as CustomValue).useValue);
  }
 
  public isCustomFactory(component): component is CustomFactory {
    return !isUndefined((component as CustomFactory).useFactory);
  }
 
  public isDynamicModule(exported): exported is DynamicModule {
    return exported && exported.module;
  }
 
  public addCustomClass(component: CustomClass, collection: Map<string, any>) {
    const { name, useClass } = component;
    collection.set(name, {
      name,
      metatype: useClass,
      instance: null,
      isResolved: false,
    });
  }
 
  public addCustomValue(component: CustomValue, collection: Map<string, any>) {
    const { name, useValue: value } = component;
    collection.set(name, {
      name,
      metatype: null,
      instance: value,
      isResolved: true,
      isNotMetatype: true,
      async: value instanceof Promise,
    });
  }
 
  public addCustomFactory(
    component: CustomFactory,
    collection: Map<string, any>,
  ) {
    const { name, useFactory: factory, inject } = component;
    collection.set(name, {
      name,
      metatype: factory as any,
      instance: null,
      isResolved: false,
      inject: inject || [],
      isNotMetatype: true,
    });
  }
 
  public addExportedComponent(
    exportedComponent: ComponentMetatype | string | symbol | DynamicModule,
  ) {
    const addExportedUnit = (token: string | symbol) =>
      this._exports.add(this.validateExportedProvider(token));
 
    if (this.isCustomProvider(exportedComponent as any)) {
      return this.addCustomExportedComponent(exportedComponent as any);
    } else Iif (isString(exportedComponent) || isSymbol(exportedComponent)) {
      return addExportedUnit(exportedComponent);
    } else Iif (this.isDynamicModule(exportedComponent)) {
      const { module } = exportedComponent;
      return addExportedUnit(module.name);
    }
    addExportedUnit(exportedComponent.name);
  }
 
  public addCustomExportedComponent(
    exportedComponent: CustomFactory | CustomValue | CustomClass,
  ) {
    const provide = exportedComponent.provide;
    Eif (isString(provide) || isSymbol(provide)) {
      return this._exports.add(this.validateExportedProvider(provide));
    }
    this._exports.add(this.validateExportedProvider(provide.name));
  }
 
  public validateExportedProvider(token: string | symbol) {
    if (this._components.has(token)) {
      return token;
    }
    const importedArray = [...this._relatedModules.values()];
    const importedRefNames = importedArray
      .filter(item => item)
      .map(({ metatype }) => metatype)
      .filter(metatype => metatype)
      .map(({ name }) => name);
 
    if (!importedRefNames.includes(token as any)) {
      const { name } = this.metatype;
      throw new UnknownExportException(name);
    }
    return token;
  }
 
  public addRoute(route: Type<Controller>) {
    this._routes.set(route.name, {
      name: route.name,
      metatype: route,
      instance: null,
      isResolved: false,
    });
  }
 
  public addRelatedModule(relatedModule) {
    this._relatedModules.add(relatedModule);
  }
 
  public replace(toReplace, options) {
    if (options.isComponent) {
      return this.addComponent({ provide: toReplace, ...options });
    }
    this.addInjectable({
      provide: toReplace,
      ...options,
    });
  }
 
  public createModuleRefMetatype(): any {
    const self = this;
    return class extends ModuleRef {
      constructor() {
        super(self.container);
      }
 
      public get<TInput = any, TResult = TInput>(
        typeOrToken: Type<TInput> | string | symbol,
        options: { strict: boolean } = { strict: true },
      ): TResult {
        Iif (!(options && options.strict)) {
          return this.find<TInput, TResult>(typeOrToken);
        }
        return this.findInstanceByPrototypeOrToken<TInput, TResult>(
          typeOrToken,
          self,
        );
      }
 
      public async create<T = any>(type: Type<T>): Promise<T> {
        if (!(type && isFunction(type) && type.prototype)) {
          throw new InvalidClassException(type);
        }
        return this.instantiateClass<T>(type, self);
      }
    };
  }
}