All files / core/helpers execution-context.host.ts

100% Statements 16/16
100% Branches 2/2
100% Functions 13/13
100% Lines 16/16
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                1x   21x 21x 21x       2x       2x       1x       9x       1x 1x         1x 1x 1x         1x 1x 1x        
import { ExecutionContext } from '@nestjs/common';
import { Type } from '@nestjs/common/interfaces';
import {
  RpcArgumentsHost,
  WsArgumentsHost,
  HttpArgumentsHost,
} from '@nestjs/common/interfaces/features/arguments-host.interface';
 
export class ExecutionContextHost implements ExecutionContext {
  constructor(
    private readonly args: any[],
    private readonly constructorRef: Type<any> = null,
    private readonly handler: Function = null,
  ) {}
 
  getClass<T = any>(): Type<T> {
    return this.constructorRef;
  }
 
  getHandler(): Function {
    return this.handler;
  }
 
  getArgs<T extends Array<any> = any[]>(): T {
    return this.args as T;
  }
 
  getArgByIndex<T = any>(index: number): T {
    return this.args[index] as T;
  }
 
  switchToRpc(): RpcArgumentsHost {
    return Object.assign(this, {
      getData: () => this.getArgByIndex(0),
    });
  }
 
  switchToHttp(): HttpArgumentsHost {
    return Object.assign(this, {
      getRequest: () => this.getArgByIndex(0),
      getResponse: () => this.getArgByIndex(1),
    });
  }
 
  switchToWs(): WsArgumentsHost {
    return Object.assign(this, {
      getClient: () => this.getArgByIndex(0),
      getData: () => this.getArgByIndex(1),
    });
  }
}