Skip to content

Commit bffdb8a

Browse files
committed
feat: add contextFactory param to RequireFlagsEnabled decorator
Signed-off-by: Kaushal Kapasi <[email protected]>
1 parent a68c228 commit bffdb8a

File tree

1 file changed

+15
-1
lines changed

1 file changed

+15
-1
lines changed

packages/nest/src/require-flags-enabled.decorator.ts

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import type { CallHandler, ExecutionContext, HttpException, NestInterceptor } fr
22
import { applyDecorators, mixin, NotFoundException, UseInterceptors } from '@nestjs/common';
33
import { getClientForEvaluation } from './utils';
44
import type { EvaluationContext } from '@openfeature/server-sdk';
5+
import type { ContextFactory } from './context-factory';
56

67
type RequiredFlag = {
78
flagKey: string;
@@ -37,6 +38,13 @@ interface RequireFlagsEnabledProps {
3738
* @see {@link OpenFeature#setContext}
3839
*/
3940
context?: EvaluationContext;
41+
42+
/**
43+
* A factory function for creating an OpenFeature {@link EvaluationContext} from Nest {@link ExecutionContext}.
44+
* For example, this can be used to get header info from an HTTP request or information from a gRPC call to be used in the {@link EvaluationContext}.
45+
* @see {@link ContextFactory}
46+
*/
47+
contextFactory?: ContextFactory;
4048
}
4149

4250
/**
@@ -56,6 +64,11 @@ interface RequireFlagsEnabledProps {
5664
* context: { // Optional, defaults to the global OpenFeature Context
5765
* targetingKey: 'user-id',
5866
* },
67+
* contextFactory: (context: ExecutionContext) => { // Optional, defaults to the global OpenFeature Context. Takes precedence over the context option.
68+
* return {
69+
* targetingKey: context.switchToHttp().getRequest().headers['x-user-id'],
70+
* };
71+
* },
5972
* })
6073
* @Get('/')
6174
* public async handleGetRequest()
@@ -72,7 +85,8 @@ const FlagsEnabledInterceptor = (props: RequireFlagsEnabledProps) => {
7285

7386
async intercept(context: ExecutionContext, next: CallHandler) {
7487
const req = context.switchToHttp().getRequest();
75-
const client = getClientForEvaluation(props.domain, props.context);
88+
const evaluationContext = props.contextFactory ? await props.contextFactory(context) : props.context;
89+
const client = getClientForEvaluation(props.domain, evaluationContext);
7690

7791
for (const flag of props.flags) {
7892
const endpointAccessible = await client.getBooleanValue(flag.flagKey, flag.defaultValue ?? false);

0 commit comments

Comments
 (0)