/
use-guards.decorator.ts
56 lines (54 loc) 路 1.78 KB
/
use-guards.decorator.ts
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
import { GUARDS_METADATA } from '../../constants';
import { CanActivate } from '../../interfaces';
import { extendArrayMetadata } from '../../utils/extend-metadata.util';
import { isFunction } from '../../utils/shared.utils';
import { validateEach } from '../../utils/validate-each.util';
/**
* 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: (CanActivate | Function)[]
): MethodDecorator & ClassDecorator {
return (
target: any,
key?: string | symbol,
descriptor?: TypedPropertyDescriptor<any>,
) => {
const isGuardValid = <T extends Function | Record<string, any>>(guard: T) =>
guard &&
(isFunction(guard) ||
isFunction((guard as Record<string, any>).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;
};
}