|
| 1 | +import type { Adapter } from 'flags'; |
| 2 | +import { createClient } from '@vercel/edge-config'; |
| 3 | +import { |
| 4 | + init, |
| 5 | + LDClient, |
| 6 | + type LDContext, |
| 7 | +} from '@launchdarkly/vercel-server-sdk'; |
| 8 | + |
1 | 9 | export { getProviderData } from './provider';
|
| 10 | +export type { LDContext }; |
| 11 | + |
| 12 | +interface AdapterOptions<ValueType> { |
| 13 | + defaultValue?: ValueType; |
| 14 | +} |
| 15 | + |
| 16 | +let defaultLaunchDarklyAdapter: |
| 17 | + | ReturnType<typeof createLaunchDarklyAdapter> |
| 18 | + | undefined; |
| 19 | + |
| 20 | +function assertEnv(name: string): string { |
| 21 | + const value = process.env[name]; |
| 22 | + if (!value) { |
| 23 | + throw new Error( |
| 24 | + `LaunchDarkly Adapter: Missing ${name} environment variable`, |
| 25 | + ); |
| 26 | + } |
| 27 | + return value; |
| 28 | +} |
| 29 | + |
| 30 | +export function createLaunchDarklyAdapter({ |
| 31 | + projectSlug, |
| 32 | + clientSideId, |
| 33 | + edgeConfigConnectionString, |
| 34 | +}: { |
| 35 | + projectSlug: string; |
| 36 | + clientSideId: string; |
| 37 | + edgeConfigConnectionString: string; |
| 38 | +}) { |
| 39 | + const edgeConfigClient = createClient(edgeConfigConnectionString); |
| 40 | + const ldClient = init(clientSideId, edgeConfigClient); |
| 41 | + |
| 42 | + return function launchDarklyAdapter<ValueType>( |
| 43 | + options: AdapterOptions<ValueType> = {}, |
| 44 | + ): Adapter<ValueType, LDContext> & { ldClient: LDClient } { |
| 45 | + return { |
| 46 | + /** The LaunchDarkly client instance used by the adapter. */ |
| 47 | + ldClient, |
| 48 | + origin(key) { |
| 49 | + return `https://app.launchdarkly.com/projects/${projectSlug}/flags/${key}/`; |
| 50 | + }, |
| 51 | + async decide({ key, entities }): Promise<ValueType> { |
| 52 | + await ldClient.waitForInitialization(); |
| 53 | + return ldClient.variation( |
| 54 | + key, |
| 55 | + entities as LDContext, |
| 56 | + options.defaultValue, |
| 57 | + ) as ValueType; |
| 58 | + }, |
| 59 | + }; |
| 60 | + }; |
| 61 | +} |
| 62 | + |
| 63 | +export function launchDarkly<ValueType>( |
| 64 | + options?: AdapterOptions<ValueType>, |
| 65 | +): Adapter<ValueType, LDContext> { |
| 66 | + if (!defaultLaunchDarklyAdapter) { |
| 67 | + const edgeConfigConnectionString = assertEnv('EDGE_CONFIG'); |
| 68 | + const clientSideId = assertEnv('LAUNCHDARKLY_CLIENT_SIDE_ID'); |
| 69 | + const projectSlug = assertEnv('LAUNCHDARKLY_PROJECT_SLUG'); |
| 70 | + |
| 71 | + defaultLaunchDarklyAdapter = createLaunchDarklyAdapter({ |
| 72 | + projectSlug, |
| 73 | + clientSideId, |
| 74 | + edgeConfigConnectionString, |
| 75 | + }); |
| 76 | + } |
| 77 | + |
| 78 | + return defaultLaunchDarklyAdapter(options); |
| 79 | +} |
0 commit comments