forked from open-feature/js-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathevaluation-context-interceptor.ts
47 lines (44 loc) · 1.87 KB
/
evaluation-context-interceptor.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
import { CallHandler, ExecutionContext, Inject, Injectable, NestInterceptor } from '@nestjs/common';
import { ContextFactory, ContextFactoryToken } from './context-factory';
import { Observable } from 'rxjs';
import { OpenFeature } from '@openfeature/server-sdk';
import { OpenFeatureModule } from './open-feature.module';
/**
* NestJS interceptor used in {@link OpenFeatureModule}
* to configure flag evaluation context.
*
* This interceptor is configured globally by default.
* If `useGlobalInterceptor` is set to `false` in {@link OpenFeatureModule} it needs to be configured for the specific controllers or routes.
*
* If just the interceptor class is passed to the `UseInterceptors` like below, the `contextFactory` provided in the {@link OpenFeatureModule} will be injected and used in order to create the context.
* ```ts
* //route interceptor
* @UseInterceptors(EvaluationContextInterceptor)
* @Get('/user-info')
* getUserInfo(){}
* ```
*
* A different `contextFactory` can also be provided, but the interceptor instance has to be instantiated like in the following example.
* ```ts
* //route interceptor
* @UseInterceptors(new EvaluationContextInterceptor(<context factory>))
* @Get('/user-info')
* getUserInfo(){}
* ```
*/
@Injectable()
export class EvaluationContextInterceptor implements NestInterceptor {
constructor(@Inject(ContextFactoryToken) private contextFactory?: ContextFactory) {}
async intercept(executionContext: ExecutionContext, next: CallHandler) {
const context = await this.contextFactory?.(executionContext);
return new Observable((subscriber) => {
OpenFeature.setTransactionContext(context ?? {}, async () => {
next.handle().subscribe({
next: (res) => subscriber.next(res),
error: (err) => subscriber.error(err),
complete: () => subscriber.complete(),
});
});
});
}
}