-
Notifications
You must be signed in to change notification settings - Fork 37
feat: adds RequireFlagsEnabled decorator #1159
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
beeme1mr
merged 10 commits into
open-feature:main
from
kaushalkapasi:feat/require-flags-decorator
Apr 24, 2025
Merged
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
2911985
feat: adds `RequireFlagsEnabled` decorator to allow reusable controll…
kaushalkapasi 457e272
fix: update imports for types and cleanup js docs on the require flag…
kaushalkapasi 60b1fc5
feat: add tests for RequireFlagsEnabled decorator
kaushalkapasi 32a3e7f
feat: update options for RequireFlagsEnabled decorator to include con…
kaushalkapasi c99945d
fixup: restore sm
toddbaert 0118d87
chore: remove unused import to fix lint errors
kaushalkapasi a68c228
fix: update docs for context definition on RequireFlagsEnabledProps. …
kaushalkapasi bffdb8a
feat: add contextFactory param to RequireFlagsEnabled decorator
kaushalkapasi 2957832
chore: update NestJS readme with a simple example of how to implement…
kaushalkapasi a236d45
Merge branch 'main' into feat/require-flags-decorator
toddbaert File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,104 @@ | ||
import type { CallHandler, ExecutionContext, HttpException, NestInterceptor } from '@nestjs/common'; | ||
import { applyDecorators, mixin, NotFoundException, UseInterceptors } from '@nestjs/common'; | ||
import { getClientForEvaluation } from './utils'; | ||
import type { EvaluationContext } from '@openfeature/server-sdk'; | ||
import type { ContextFactory } from './context-factory'; | ||
|
||
type RequiredFlag = { | ||
flagKey: string; | ||
defaultValue?: boolean; | ||
}; | ||
|
||
/** | ||
* Options for using one or more Boolean feature flags to control access to a Controller or Route. | ||
*/ | ||
interface RequireFlagsEnabledProps { | ||
beeme1mr marked this conversation as resolved.
Show resolved
Hide resolved
|
||
/** | ||
* The key and default value of the feature flag. | ||
* @see {@link Client#getBooleanValue} | ||
*/ | ||
flags: RequiredFlag[]; | ||
|
||
/** | ||
* The exception to throw if any of the required feature flags are not enabled. | ||
* Defaults to a 404 Not Found exception. | ||
lukas-reining marked this conversation as resolved.
Show resolved
Hide resolved
|
||
* @see {@link HttpException} | ||
* @default new NotFoundException(`Cannot ${req.method} ${req.url}`) | ||
*/ | ||
exception?: HttpException; | ||
lukas-reining marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
/** | ||
* The domain of the OpenFeature client, if a domain scoped client should be used. | ||
* @see {@link OpenFeature#getClient} | ||
*/ | ||
domain?: string; | ||
|
||
/** | ||
* The {@link EvaluationContext} for evaluating the feature flag. | ||
* @see {@link OpenFeature#setContext} | ||
*/ | ||
context?: EvaluationContext; | ||
lukas-reining marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
/** | ||
* A factory function for creating an OpenFeature {@link EvaluationContext} from Nest {@link ExecutionContext}. | ||
* 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}. | ||
* @see {@link ContextFactory} | ||
*/ | ||
contextFactory?: ContextFactory; | ||
} | ||
|
||
/** | ||
* Controller or Route permissions handler decorator. | ||
* | ||
* Requires that the given feature flags are enabled for the request to be processed, else throws an exception. | ||
* | ||
* For example: | ||
* ```typescript | ||
* @RequireFlagsEnabled({ | ||
* flags: [ // Required, an array of Boolean flags to check, with optional default values (defaults to false) | ||
* { flagKey: 'flagName' }, | ||
* { flagKey: 'flagName2', defaultValue: true }, | ||
* ], | ||
* exception: new ForbiddenException(), // Optional, defaults to a 404 Not Found Exception | ||
* domain: 'my-domain', // Optional, defaults to the default OpenFeature Client | ||
* context: { // Optional, defaults to the global OpenFeature Context | ||
* targetingKey: 'user-id', | ||
* }, | ||
* contextFactory: (context: ExecutionContext) => { // Optional, defaults to the global OpenFeature Context. Takes precedence over the context option. | ||
* return { | ||
* targetingKey: context.switchToHttp().getRequest().headers['x-user-id'], | ||
* }; | ||
* }, | ||
* }) | ||
* @Get('/') | ||
* public async handleGetRequest() | ||
* ``` | ||
* @param {RequireFlagsEnabledProps} props The options for injecting the feature flag. | ||
* @returns {ClassDecorator & MethodDecorator} The decorator that can be used to require Boolean Feature Flags to be enabled for a controller or a specific route. | ||
*/ | ||
export const RequireFlagsEnabled = (props: RequireFlagsEnabledProps): ClassDecorator & MethodDecorator => | ||
applyDecorators(UseInterceptors(FlagsEnabledInterceptor(props))); | ||
beeme1mr marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
const FlagsEnabledInterceptor = (props: RequireFlagsEnabledProps) => { | ||
class FlagsEnabledInterceptor implements NestInterceptor { | ||
constructor() {} | ||
|
||
async intercept(context: ExecutionContext, next: CallHandler) { | ||
const req = context.switchToHttp().getRequest(); | ||
const evaluationContext = props.contextFactory ? await props.contextFactory(context) : props.context; | ||
const client = getClientForEvaluation(props.domain, evaluationContext); | ||
|
||
for (const flag of props.flags) { | ||
const endpointAccessible = await client.getBooleanValue(flag.flagKey, flag.defaultValue ?? false); | ||
|
||
if (!endpointAccessible) { | ||
throw props.exception || new NotFoundException(`Cannot ${req.method} ${req.url}`); | ||
} | ||
} | ||
|
||
return next.handle(); | ||
} | ||
} | ||
|
||
return mixin(FlagsEnabledInterceptor); | ||
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,12 @@ | ||
import type { Client, EvaluationContext } from '@openfeature/server-sdk'; | ||
import { OpenFeature } from '@openfeature/server-sdk'; | ||
|
||
/** | ||
* Returns a domain scoped or the default OpenFeature client with the given context. | ||
* @param {string} domain The domain of the OpenFeature client. | ||
* @param {EvaluationContext} context The evaluation context of the client. | ||
* @returns {Client} The OpenFeature client. | ||
*/ | ||
export function getClientForEvaluation(domain?: string, context?: EvaluationContext) { | ||
return domain ? OpenFeature.getClient(domain, context) : OpenFeature.getClient(context); | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.