Skip to content

Commit 5f8eab7

Browse files
committed
fix(application-generic): improve LaunchDarkly client initialization and error handling
1 parent d2b82d2 commit 5f8eab7

File tree

1 file changed

+20
-10
lines changed

1 file changed

+20
-10
lines changed

libs/application-generic/src/services/feature-flags/launch-darkly.service.ts

Lines changed: 20 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,27 @@
11
import { init, LDClient, LDMultiKindContext } from '@launchdarkly/node-server-sdk';
2-
import { Injectable } from '@nestjs/common';
2+
import { Injectable, Logger } from '@nestjs/common';
33
import type { FeatureFlagContext, FeatureFlagContextBase, IFeatureFlagsService } from './types';
44

5+
const LOG_CONTEXT = 'LaunchDarklyFeatureFlagsService';
6+
const INITIALIZATION_TIMEOUT_SECONDS = 10;
7+
58
@Injectable()
69
export class LaunchDarklyFeatureFlagsService implements IFeatureFlagsService {
710
private client: LDClient;
8-
public isEnabled: boolean;
11+
public isEnabled = false;
912

1013
public async initialize(): Promise<void> {
11-
const launchDarklySdkKey = process.env.LAUNCH_DARKLY_SDK_KEY;
12-
if (!launchDarklySdkKey) {
13-
throw new Error('Missing Launch Darkly SDK key');
14+
try {
15+
this.client = init(process.env.LAUNCH_DARKLY_SDK_KEY as string);
16+
await this.client.waitForInitialization({ timeout: INITIALIZATION_TIMEOUT_SECONDS });
17+
this.isEnabled = true;
18+
} catch (error) {
19+
Logger.error(
20+
`Failed to initialize LaunchDarkly client, feature flags will use default values. SDK will retry to initialize in the next tick.`,
21+
(error as Error).stack || (error as Error).message,
22+
LOG_CONTEXT
23+
);
1424
}
15-
this.client = init(launchDarklySdkKey);
16-
await this.client.waitForInitialization({ timeout: 10000 });
17-
this.isEnabled = true;
1825
}
1926

2027
public async gracefullyShutdown(): Promise<void> {
@@ -32,10 +39,13 @@ export class LaunchDarklyFeatureFlagsService implements IFeatureFlagsService {
3239
user,
3340
component,
3441
}: FeatureFlagContext<T_Result>): Promise<T_Result> {
42+
if (!this.isEnabled) {
43+
return defaultValue;
44+
}
45+
3546
const context = this.buildLDContext({ user, organization, environment, component });
36-
const newVar = await this.client.variation(key, context, defaultValue);
3747

38-
return newVar;
48+
return await this.client.variation(key, context, defaultValue);
3949
}
4050

4151
private buildLDContext({ user, organization, environment, component }: FeatureFlagContextBase): LDMultiKindContext {

0 commit comments

Comments
 (0)