-
Notifications
You must be signed in to change notification settings - Fork 59
feat: nestjs async factory #1328
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
Open
imranismail
wants to merge
4
commits into
open-feature:main
Choose a base branch
from
imranismail:feat/nest-async-registration
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 3 commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
b657a92
feat: nestjs async factory
imranismail a6ac90f
Merge branch 'main' into feat/nest-async-registration
lukas-reining 88767e8
fix: Import InMemoryProvider for OpenFeature testing
imranismail 9873a90
Merge branch 'main' into feat/nest-async-registration
lukas-reining 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
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
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 |
|---|---|---|
| @@ -1,13 +1,6 @@ | ||
| import type { DynamicModule } from '@nestjs/common'; | ||
| import { Module, ConfigurableModuleBuilder } from '@nestjs/common'; | ||
| import type { | ||
| DynamicModule, | ||
| FactoryProvider as NestFactoryProvider, | ||
| ValueProvider, | ||
| ClassProvider, | ||
| Provider as NestProvider, | ||
| } from '@nestjs/common'; | ||
| import { Module, ExecutionContext } from '@nestjs/common'; | ||
| import type { | ||
| Client, | ||
| Hook, | ||
| Provider, | ||
| EvaluationContext, | ||
|
|
@@ -22,73 +15,105 @@ | |
| import { EvaluationContextInterceptor } from './evaluation-context-interceptor'; | ||
| import { ShutdownService } from './shutdown.service'; | ||
|
|
||
| export const OPEN_FEATURE_INIT_TOKEN = Symbol('OPEN_FEATURE_INIT'); | ||
|
|
||
| /** | ||
|
Check warning on line 20 in packages/nest/src/open-feature.module.ts
|
||
| * OpenFeatureModule is a NestJS wrapper for OpenFeature Server-SDK. | ||
| * Initialize OpenFeature with the provided options. | ||
| */ | ||
| @Module({}) | ||
| export class OpenFeatureModule { | ||
| static forRoot({ useGlobalInterceptor = true, ...options }: OpenFeatureModuleOptions): DynamicModule { | ||
| OpenFeature.setTransactionContextPropagator(new AsyncLocalStorageTransactionContextPropagator()); | ||
|
|
||
| if (options.logger) { | ||
| OpenFeature.setLogger(options.logger); | ||
| } | ||
|
|
||
| if (options.hooks) { | ||
| OpenFeature.addHooks(...options.hooks); | ||
| } | ||
|
|
||
| options.handlers?.forEach(([event, handler]) => { | ||
| OpenFeature.addHandler(event, handler); | ||
| }); | ||
|
|
||
| const clientValueProviders: NestFactoryProvider<Client>[] = [ | ||
| { | ||
| provide: getOpenFeatureClientToken(), | ||
| useFactory: () => OpenFeature.getClient(), | ||
| }, | ||
| ]; | ||
|
|
||
| if (options?.defaultProvider) { | ||
| OpenFeature.setProvider(options.defaultProvider); | ||
| } | ||
|
|
||
| if (options?.providers) { | ||
| Object.entries(options.providers).forEach(([domain, provider]) => { | ||
| OpenFeature.setProvider(domain, provider); | ||
| clientValueProviders.push({ | ||
| provide: getOpenFeatureClientToken(domain), | ||
| useFactory: () => OpenFeature.getClient(domain), | ||
| }); | ||
| }); | ||
| } | ||
|
|
||
| const nestProviders: NestProvider[] = [ShutdownService]; | ||
| nestProviders.push(...clientValueProviders); | ||
|
|
||
| const contextFactoryProvider: ValueProvider = { | ||
| provide: ContextFactoryToken, | ||
| useValue: options?.contextFactory, | ||
| }; | ||
| nestProviders.push(contextFactoryProvider); | ||
|
|
||
| if (useGlobalInterceptor) { | ||
| const interceptorProvider: ClassProvider = { | ||
| provide: APP_INTERCEPTOR, | ||
| useClass: EvaluationContextInterceptor, | ||
| }; | ||
| nestProviders.push(interceptorProvider); | ||
| } | ||
|
|
||
| return { | ||
| global: true, | ||
| module: OpenFeatureModule, | ||
| providers: nestProviders, | ||
| exports: [...clientValueProviders, ContextFactoryToken], | ||
| }; | ||
| async function initializeOpenFeature(options: OpenFeatureModuleOptions): Promise<OpenFeatureModuleOptions> { | ||
| OpenFeature.setTransactionContextPropagator(new AsyncLocalStorageTransactionContextPropagator()); | ||
|
|
||
| if (options.logger) { | ||
| OpenFeature.setLogger(options.logger); | ||
| } | ||
|
|
||
| if (options.hooks) { | ||
| OpenFeature.addHooks(...options.hooks); | ||
| } | ||
|
|
||
| options.handlers?.forEach(([event, handler]) => { | ||
| OpenFeature.addHandler(event, handler); | ||
| }); | ||
|
|
||
| if (options.defaultProvider) { | ||
| await OpenFeature.setProviderAndWait(options.defaultProvider); | ||
| } | ||
|
|
||
| if (options.providers) { | ||
| await Promise.all( | ||
| Object.entries(options.providers).map(([domain, provider]) => OpenFeature.setProviderAndWait(domain, provider)), | ||
| ); | ||
| } | ||
|
|
||
| return options; | ||
| } | ||
|
|
||
| export const { ConfigurableModuleClass, MODULE_OPTIONS_TOKEN, OPTIONS_TYPE, ASYNC_OPTIONS_TYPE } = | ||
| new ConfigurableModuleBuilder<OpenFeatureModuleOptions>() | ||
| .setClassMethodName('forRoot') | ||
| .setExtras<OpenFeatureModuleExtras>( | ||
| { isGlobal: true, useGlobalInterceptor: true, domains: [] }, | ||
| (definition, extras) => { | ||
| const moduleProviders: DynamicModule['providers'] = [ | ||
| ...(definition.providers || []), | ||
| ShutdownService, | ||
| { | ||
| provide: OPEN_FEATURE_INIT_TOKEN, | ||
| inject: [MODULE_OPTIONS_TOKEN], | ||
| useFactory: initializeOpenFeature, | ||
| }, | ||
| // Default client | ||
| { | ||
| provide: getOpenFeatureClientToken(), | ||
| inject: [OPEN_FEATURE_INIT_TOKEN], | ||
| useFactory: () => OpenFeature.getClient(), | ||
| }, | ||
| // Context factory | ||
| { | ||
| provide: ContextFactoryToken, | ||
| inject: [OPEN_FEATURE_INIT_TOKEN], | ||
| useFactory: (options: OpenFeatureModuleOptions) => options.contextFactory, | ||
| }, | ||
| ]; | ||
|
|
||
| const moduleExports: DynamicModule['exports'] = [ | ||
| ...(definition.exports || []), | ||
| ContextFactoryToken, | ||
| getOpenFeatureClientToken(), | ||
| ]; | ||
|
|
||
| if (extras.useGlobalInterceptor) { | ||
| moduleProviders.push({ | ||
| provide: APP_INTERCEPTOR, | ||
| useClass: EvaluationContextInterceptor, | ||
| }); | ||
| } | ||
|
|
||
| for (const domain of extras.domains || []) { | ||
| moduleProviders.push({ | ||
| provide: getOpenFeatureClientToken(domain), | ||
| useFactory: () => OpenFeature.getClient(domain), | ||
| inject: [OPEN_FEATURE_INIT_TOKEN], | ||
| }); | ||
| moduleExports.push(getOpenFeatureClientToken(domain)); | ||
| } | ||
|
|
||
| return { | ||
| ...definition, | ||
| global: extras.isGlobal, | ||
| providers: moduleProviders, | ||
| exports: moduleExports, | ||
| }; | ||
| }, | ||
| ) | ||
| .build(); | ||
|
|
||
| /** | ||
| * OpenFeatureModule is a NestJS wrapper for OpenFeature Server-SDK. | ||
| */ | ||
| @Module({}) | ||
| export class OpenFeatureModule extends ConfigurableModuleClass {} | ||
|
|
||
| /** | ||
| * Options for the {@link OpenFeatureModule}. | ||
| */ | ||
|
|
@@ -126,12 +151,18 @@ | |
| */ | ||
| handlers?: [ServerProviderEvents, EventHandler][]; | ||
| /** | ||
| * The {@link ContextFactory} for creating an {@link EvaluationContext} from Nest {@link ExecutionContext} information. | ||
| * This could be header values of a request or something similar. | ||
| * The context is automatically used for all feature flag evaluations during this request. | ||
| * @see {@link AsyncLocalStorageTransactionContextPropagator} | ||
| */ | ||
| contextFactory?: ContextFactory; | ||
| } | ||
|
|
||
| /** | ||
| * Extra options available at module definition time | ||
| */ | ||
| export interface OpenFeatureModuleExtras { | ||
| /** | ||
| * If set to false, the global {@link EvaluationContextInterceptor} is disabled. | ||
| * This means that automatic propagation of the {@link EvaluationContext} created by the {@link this#contextFactory} is not working. | ||
|
|
@@ -145,12 +176,22 @@ | |
| * @default true | ||
| */ | ||
| useGlobalInterceptor?: boolean; | ||
| /** | ||
| * Whether the module should be global. | ||
| * @default true | ||
| */ | ||
| isGlobal?: boolean; | ||
| /** | ||
| * Domains for which to create domain-scoped OpenFeature clients. | ||
| * Each domain will get its own injectable client token via {@link getOpenFeatureClientToken}. | ||
| */ | ||
| domains?: string[]; | ||
| } | ||
|
|
||
| /** | ||
| * Returns an injection token for a (domain scoped) OpenFeature client. | ||
| * @param {string} domain The domain of the OpenFeature client. | ||
| * @returns {Client} The injection token. | ||
| */ | ||
| export function getOpenFeatureClientToken(domain?: string): string { | ||
| return domain ? `OpenFeatureClient_${domain}` : 'OpenFeatureClient_default'; | ||
|
|
||
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
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.