# All files / common/decorators/core use-guards.decorator.ts

100% Statements 15/15
80% Branches 4/5
100% Functions 3/3
100% Lines 15/15

    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
    381x
    1x
    1x
    1x

    1x
    8x
    8x
    11x

    8x
    4x

    4x
    4x

    4x
    4x
    4x

     import { GUARDS_METADATA } from '../../constants';
    import { extendArrayMetadata } from '../../utils/extend-metadata.util';
    import { validateEach } from '../../utils/validate-each.util';
    import { isFunction } from '../../utils/shared.utils';
    import { CanActivate } from '../../interfaces';

    /**
     * Binds guards to the particular context.
     * When the `@UseGuards()` is used on the controller level:
     * - Guard will be register to each handler (every method)
     *
     * When the `@UseGuards()` is used on the handler level:
     * - Guard will be registered only to specified method
     *
     * @param  {} ...guards
     */
    export function UseGuards(...guards: (CanActivate | Function)[]) {
      return (target: any, key?, descriptor?) => {
        const isValidGuard = guard =>
          guard && (isFunction(guard) || isFunction(guard.canActivate));

        if (descriptor) {
          validateEach(
            target.constructor,
            guards,
            isValidGuard,
            '@UseGuards',
            'guard',
          );
          extendArrayMetadata(GUARDS_METADATA, guards, descriptor.value);
          return descriptor;
        }
        validateEach(target, guards, isValidGuard, '@UseGuards', 'guard');
        extendArrayMetadata(GUARDS_METADATA, guards, target);
        return target;
      };
    }