All files / core/middleware container.ts

100% Statements 19/19
62.5% Branches 5/8
100% Functions 8/8
100% Lines 19/19
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        1x 7x       7x           7x       1x       5x 5x   5x 5x 4x 4x 4x         4x         5x 5x   5x       5x 5x   5x                
import { MiddlewareConfiguration } from '@nestjs/common/interfaces/middleware/middleware-configuration.interface';
import { NestMiddleware } from '@nestjs/common/interfaces/middleware/nest-middleware.interface';
import { Type } from '@nestjs/common/interfaces/type.interface';
 
export class MiddlewareContainer {
  private readonly middleware = new Map<
    string,
    Map<string, MiddlewareWrapper>
  >();
  private readonly configurationSets = new Map<
    string,
    Set<MiddlewareConfiguration>
  >();
 
  public getMiddleware(module: string): Map<string, MiddlewareWrapper> {
    return this.middleware.get(module) || new Map();
  }
 
  public getConfigs(): Map<string, Set<MiddlewareConfiguration>> {
    return this.configurationSets;
  }
 
  public addConfig(configList: MiddlewareConfiguration[], module: string) {
    const middleware = this.getCurrentMiddleware(module);
    const currentConfig = this.getCurrentConfig(module);
 
    const configurations = configList || [];
    configurations.forEach(config => {
      [].concat(config.middleware).map(metatype => {
        const token = metatype.name;
        middleware.set(token, {
          instance: null,
          metatype,
        });
      });
      currentConfig.add(config);
    });
  }
 
  private getCurrentMiddleware(module: string) {
    Eif (!this.middleware.has(module)) {
      this.middleware.set(module, new Map<string, MiddlewareWrapper>());
    }
    return this.middleware.get(module);
  }
 
  private getCurrentConfig(module: string) {
    Eif (!this.configurationSets.has(module)) {
      this.configurationSets.set(module, new Set<MiddlewareConfiguration>());
    }
    return this.configurationSets.get(module);
  }
}
 
export interface MiddlewareWrapper {
  instance: NestMiddleware;
  metatype: Type<NestMiddleware>;
}