# All files / core/guards guards-consumer.ts

100% Statements 17/17
100% Branches 8/8
100% Functions 3/3
100% Lines 17/17

    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
    491x

    1x
    1x

    1x

    5x
    1x

    4x
    4x
    7x
    7x
    6x

    1x

    3x

    4x

    9x
    1x

    8x

     import { isEmpty } from '@nestjs/common/utils/shared.utils';
    import { Controller } from '@nestjs/common/interfaces';
    import { CanActivate } from '@nestjs/common';
    import { Observable } from 'rxjs';
    import { ExecutionContextHost } from '../helpers/execution-context.host';

    export class GuardsConsumer {
      public async tryActivate(
        guards: CanActivate[],
        args: any[],
        instance: Controller,
        callback: (...args) => any,
      ): Promise<boolean> {
        if (!guards || isEmpty(guards)) {
          return true;
        }
        const context = this.createContext(args, instance, callback);
        for (const guard of guards) {
          const result = guard.canActivate(context);
          if (await this.pickResult(result)) {
            continue;
          }
          return false;
        }
        return true;
      }

      public createContext(
        args: any[],
        instance: Controller,
        callback: (...args) => any,
      ): ExecutionContextHost {
        return new ExecutionContextHost(
          args,
          instance.constructor as any,
          callback,
        );
      }

      public async pickResult(
        result: boolean | Promise<boolean> | Observable<boolean>,
      ): Promise<boolean> {
        if (result instanceof Observable) {
          return result.toPromise();
        }
        return result;
      }
    }