UNPKG

@nestjs/common

Version:

Nest - modern, fast, powerful node.js web framework (@common)

39 lines (38 loc) 1.56 kB
import { GUARDS_METADATA } from '../../constants.js'; import { extendArrayMetadata } from '../../utils/extend-metadata.util.js'; import { isFunction } from '../../utils/shared.utils.js'; import { validateEach } from '../../utils/validate-each.util.js'; /** * Decorator that binds guards to the scope of the controller or method, * depending on its context. * * When `@UseGuards` is used at the controller level, the guard will be * applied to every handler (method) in the controller. * * When `@UseGuards` is used at the individual handler level, the guard * will apply only to that specific method. * * @param guards a single guard instance or class, or a list of guard instances * or classes. * * @see [Guards](https://docs.nestjs.com/guards) * * @usageNotes * Guards can also be set up globally for all controllers and routes * using `app.useGlobalGuards()`. [See here for details](https://docs.nestjs.com/guards#binding-guards) * * @publicApi */ export function UseGuards(...guards) { return (target, key, descriptor) => { const isGuardValid = (guard) => guard && (isFunction(guard) || isFunction(guard.canActivate)); if (descriptor) { validateEach(target.constructor, guards, isGuardValid, '@UseGuards', 'guard'); extendArrayMetadata(GUARDS_METADATA, guards, descriptor.value); return descriptor; } validateEach(target, guards, isGuardValid, '@UseGuards', 'guard'); extendArrayMetadata(GUARDS_METADATA, guards, target); return target; }; }