|
| 1 | +import 'server-only' |
| 2 | + |
| 3 | +import type { |
| 4 | + BooleanFeatureFlagDefinition, |
| 5 | + JsonFeatureFlagDefinition, |
| 6 | +} from '@/configs/flags' |
| 7 | +import type { FeatureFlagContextInput } from '@/core/server/feature-flags/context' |
| 8 | +import { launchDarklyFeatureFlagProvider } from '@/core/server/feature-flags/launchdarkly' |
| 9 | +import { l, serializeErrorForLog } from '@/core/shared/clients/logger/logger' |
| 10 | + |
| 11 | +export type FeatureFlagProvider = { |
| 12 | + getBoolean( |
| 13 | + flag: BooleanFeatureFlagDefinition, |
| 14 | + context: FeatureFlagContextInput |
| 15 | + ): Promise<boolean> |
| 16 | + getJson<T>( |
| 17 | + flag: JsonFeatureFlagDefinition<T>, |
| 18 | + context: FeatureFlagContextInput |
| 19 | + ): Promise<unknown> |
| 20 | +} |
| 21 | + |
| 22 | +export type FeatureFlagService = { |
| 23 | + getBoolean( |
| 24 | + flag: BooleanFeatureFlagDefinition, |
| 25 | + context: FeatureFlagContextInput |
| 26 | + ): Promise<boolean> |
| 27 | + getJson<T>( |
| 28 | + flag: JsonFeatureFlagDefinition<T>, |
| 29 | + context: FeatureFlagContextInput |
| 30 | + ): Promise<T> |
| 31 | +} |
| 32 | + |
| 33 | +export function createFeatureFlagService( |
| 34 | + provider: FeatureFlagProvider = launchDarklyFeatureFlagProvider |
| 35 | +): FeatureFlagService { |
| 36 | + return { |
| 37 | + async getBoolean(flag, context) { |
| 38 | + return provider.getBoolean(flag, context) |
| 39 | + }, |
| 40 | + async getJson(flag, context) { |
| 41 | + const value = await provider.getJson(flag, context) |
| 42 | + const parsed = flag.schema.safeParse(value) |
| 43 | + |
| 44 | + if (!parsed.success) { |
| 45 | + l.warn( |
| 46 | + { |
| 47 | + key: 'feature_flags:invalid_json_flag', |
| 48 | + context: { flagKey: flag.key }, |
| 49 | + error: serializeErrorForLog(parsed.error), |
| 50 | + }, |
| 51 | + 'Feature flag JSON value has invalid shape' |
| 52 | + ) |
| 53 | + |
| 54 | + return flag.defaultValue |
| 55 | + } |
| 56 | + |
| 57 | + return parsed.data |
| 58 | + }, |
| 59 | + } |
| 60 | +} |
| 61 | + |
| 62 | +export const featureFlags = createFeatureFlagService() |
0 commit comments