-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathif-enabled.decorator.ts
43 lines (37 loc) · 1.01 KB
/
if-enabled.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
import {
applyDecorators,
CanActivate,
ExecutionContext,
Injectable,
NotFoundException,
SetMetadata,
UseGuards,
} from '@nestjs/common'
import { ModuleRef, Reflector } from '@nestjs/core'
import { UnleashService } from '../unleash.service'
@Injectable()
export class IfEnabledGuard implements CanActivate {
constructor(
private readonly reflector: Reflector,
private readonly unleash: UnleashService,
private readonly moduleRef: ModuleRef,
) {}
canActivate(context: ExecutionContext): boolean {
const toggle = this.reflector.get<string>(
METADATA_TOGGLE_NAME,
context.getHandler(),
)
if (!this.unleash.isEnabled(toggle)) {
throw new NotFoundException()
}
return true
}
}
export const METADATA_TOGGLE_NAME = 'toggleName'
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
export function IfEnabled(toggleName: string) {
return applyDecorators(
SetMetadata(METADATA_TOGGLE_NAME, toggleName),
UseGuards(IfEnabledGuard),
)
}