1
1
import type { Adapter } from 'flags' ;
2
- import { createClient } from '@vercel/edge-config' ;
2
+ import { createClient , type EdgeConfigClient } from '@vercel/edge-config' ;
3
3
import {
4
4
init ,
5
5
LDClient ,
6
6
type LDContext ,
7
7
} from '@launchdarkly/vercel-server-sdk' ;
8
+ import { AsyncLocalStorage } from 'async_hooks' ;
8
9
9
10
export { getProviderData } from './provider' ;
10
11
export type { LDContext } ;
@@ -45,7 +46,31 @@ export function createLaunchDarklyAdapter({
45
46
edgeConfigConnectionString : string ;
46
47
} ) : AdapterResponse {
47
48
const edgeConfigClient = createClient ( edgeConfigConnectionString ) ;
48
- const ldClient = init ( clientSideId , edgeConfigClient ) ;
49
+
50
+ const store = new AsyncLocalStorage < WeakKey > ( ) ;
51
+ const cache = new WeakMap < WeakKey , Promise < unknown > > ( ) ;
52
+
53
+ const patchedEdgeConfigClient : EdgeConfigClient = {
54
+ ...edgeConfigClient ,
55
+ get : async < T > ( key : string ) => {
56
+ const h = store . getStore ( ) ;
57
+ if ( h ) {
58
+ const cached = cache . get ( h ) ;
59
+ if ( cached ) {
60
+ return cached as Promise < T > ;
61
+ }
62
+ }
63
+
64
+ const promise = edgeConfigClient . get < T > ( key ) ;
65
+ if ( h ) cache . set ( h , promise ) ;
66
+
67
+ return promise ;
68
+ } ,
69
+ } ;
70
+
71
+ let initPromise : Promise < unknown > | null = null ;
72
+
73
+ const ldClient = init ( clientSideId , patchedEdgeConfigClient ) ;
49
74
50
75
function origin ( key : string ) {
51
76
return `https://app.launchdarkly.com/projects/${ projectSlug } /flags/${ key } /` ;
@@ -56,13 +81,21 @@ export function createLaunchDarklyAdapter({
56
81
) : Adapter < ValueType , LDContext > {
57
82
return {
58
83
origin,
59
- async decide ( { key, entities } ) : Promise < ValueType > {
60
- await ldClient . waitForInitialization ( ) ;
61
- return ldClient . variation (
62
- key ,
63
- entities as LDContext ,
64
- options . defaultValue ,
65
- ) as ValueType ;
84
+ async decide ( { key, entities, headers } ) : Promise < ValueType > {
85
+ if ( ! ldClient . initialized ( ) ) {
86
+ if ( ! initPromise ) initPromise = ldClient . waitForInitialization ( ) ;
87
+ await initPromise ;
88
+ }
89
+
90
+ return store . run (
91
+ headers ,
92
+ ( ) =>
93
+ ldClient . variation (
94
+ key ,
95
+ entities as LDContext ,
96
+ options . defaultValue ,
97
+ ) as ValueType ,
98
+ ) ;
66
99
} ,
67
100
} ;
68
101
}
0 commit comments