-
Notifications
You must be signed in to change notification settings - Fork 36
/
Copy pathuse-feature-flag.ts
354 lines (328 loc) · 13.5 KB
/
use-feature-flag.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
import type {
Client,
ClientProviderEvents,
EvaluationDetails,
EventHandler,
FlagEvaluationOptions,
FlagValue,
JsonValue,
} from '@openfeature/web-sdk';
import { ProviderEvents, ProviderStatus } from '@openfeature/web-sdk';
import { useEffect, useRef, useState } from 'react';
import {
DEFAULT_OPTIONS,
isEqual,
normalizeOptions,
suspendUntilInitialized,
suspendUntilReconciled,
useProviderOptions,
} from '../internal';
import type { ReactFlagEvaluationNoSuspenseOptions, ReactFlagEvaluationOptions } from '../options';
import { useOpenFeatureClient } from '../provider/use-open-feature-client';
import { useOpenFeatureClientStatus } from '../provider/use-open-feature-client-status';
import { useOpenFeatureProvider } from '../provider/use-open-feature-provider';
import type { FlagQuery } from '../query';
import { HookFlagQuery } from '../internal/hook-flag-query';
// This type is a bit wild-looking, but I think we need it.
// We have to use the conditional, because otherwise useFlag('key', false) would return false, not boolean (too constrained).
// We have a duplicate for the hook return below, this one is just used for casting because the name isn't as clear
type ConstrainedFlagQuery<T> = FlagQuery<
T extends boolean
? boolean
: T extends number
? number
: T extends string
? string
: T extends JsonValue
? T
: JsonValue
>;
/**
* Evaluates a feature flag generically, returning an react-flavored queryable object.
* The resolver method to use is based on the type of the defaultValue.
* For type-specific hooks, use {@link useBooleanFlagValue}, {@link useBooleanFlagDetails} and equivalents.
* By default, components will re-render when the flag value changes.
* @param {string} flagKey the flag identifier
* @template {FlagValue} T A optional generic argument constraining the default.
* @param {T} defaultValue the default value; used to determine what resolved type should be used.
* @param {ReactFlagEvaluationOptions} options for this evaluation
* @returns { FlagQuery } a queryable object containing useful information about the flag.
*/
export function useFlag<T extends FlagValue = FlagValue>(
flagKey: string,
defaultValue: T,
options?: ReactFlagEvaluationOptions,
): FlagQuery<
T extends boolean
? boolean
: T extends number
? number
: T extends string
? string
: T extends JsonValue
? T
: JsonValue
> {
// use the default value to determine the resolver to call
const query =
typeof defaultValue === 'boolean'
? new HookFlagQuery<boolean>(useBooleanFlagDetails(flagKey, defaultValue, options))
: typeof defaultValue === 'number'
? new HookFlagQuery<number>(useNumberFlagDetails(flagKey, defaultValue, options))
: typeof defaultValue === 'string'
? new HookFlagQuery<string>(useStringFlagDetails(flagKey, defaultValue, options))
: new HookFlagQuery<JsonValue>(useObjectFlagDetails(flagKey, defaultValue, options));
// TS sees this as HookFlagQuery<JsonValue>, because the compiler isn't aware of the `typeof` checks above.
return query as unknown as ConstrainedFlagQuery<T>;
}
// alias to the return value of useFlag, used to keep useSuspenseFlag consistent
type UseFlagReturn<T extends FlagValue> = ReturnType<typeof useFlag<T>>;
/**
* Equivalent to {@link useFlag} with `options: { suspend: true }`
* @experimental Suspense is an experimental feature subject to change in future versions.
* @param {string} flagKey the flag identifier
* @template {FlagValue} T A optional generic argument constraining the default.
* @param {T} defaultValue the default value; used to determine what resolved type should be used.
* @param {ReactFlagEvaluationNoSuspenseOptions} options for this evaluation
* @returns { UseFlagReturn<T> } a queryable object containing useful information about the flag.
*/
export function useSuspenseFlag<T extends FlagValue = FlagValue>(
flagKey: string,
defaultValue: T,
options?: ReactFlagEvaluationNoSuspenseOptions,
): UseFlagReturn<T> {
return useFlag(flagKey, defaultValue, { ...options, suspendUntilReady: true, suspendWhileReconciling: true });
}
/**
* Evaluates a feature flag, returning a boolean.
* By default, components will re-render when the flag value changes.
* For a generic hook returning a queryable interface, see {@link useFlag}.
* @param {string} flagKey the flag identifier
* @param {boolean} defaultValue the default value
* @param {ReactFlagEvaluationOptions} options options for this evaluation
* @returns { boolean} a EvaluationDetails object for this evaluation
*/
export function useBooleanFlagValue(
flagKey: string,
defaultValue: boolean,
options?: ReactFlagEvaluationOptions,
): boolean {
return useBooleanFlagDetails(flagKey, defaultValue, options).value;
}
/**
* Evaluates a feature flag, returning evaluation details.
* By default, components will re-render when the flag value changes.
* For a generic hook returning a queryable interface, see {@link useFlag}.
* @param {string} flagKey the flag identifier
* @param {boolean} defaultValue the default value
* @param {ReactFlagEvaluationOptions} options options for this evaluation
* @returns { EvaluationDetails<boolean>} a EvaluationDetails object for this evaluation
*/
export function useBooleanFlagDetails(
flagKey: string,
defaultValue: boolean,
options?: ReactFlagEvaluationOptions,
): EvaluationDetails<boolean> {
return attachHandlersAndResolve(
flagKey,
defaultValue,
(client) => {
return client.getBooleanDetails;
},
options,
);
}
/**
* Evaluates a feature flag, returning a string.
* By default, components will re-render when the flag value changes.
* For a generic hook returning a queryable interface, see {@link useFlag}.
* @param {string} flagKey the flag identifier
* @template {string} [T=string] A optional generic argument constraining the string
* @param {T} defaultValue the default value
* @param {ReactFlagEvaluationOptions} options options for this evaluation
* @returns { boolean} a EvaluationDetails object for this evaluation
*/
export function useStringFlagValue<T extends string = string>(
flagKey: string,
defaultValue: T,
options?: ReactFlagEvaluationOptions,
): string {
return useStringFlagDetails(flagKey, defaultValue, options).value;
}
/**
* Evaluates a feature flag, returning evaluation details.
* By default, components will re-render when the flag value changes.
* For a generic hook returning a queryable interface, see {@link useFlag}.
* @param {string} flagKey the flag identifier
* @template {string} [T=string] A optional generic argument constraining the string
* @param {T} defaultValue the default value
* @param {ReactFlagEvaluationOptions} options options for this evaluation
* @returns { EvaluationDetails<string>} a EvaluationDetails object for this evaluation
*/
export function useStringFlagDetails<T extends string = string>(
flagKey: string,
defaultValue: T,
options?: ReactFlagEvaluationOptions,
): EvaluationDetails<string> {
return attachHandlersAndResolve(
flagKey,
defaultValue,
(client) => {
return client.getStringDetails<T>;
},
options,
);
}
/**
* Evaluates a feature flag, returning a number.
* By default, components will re-render when the flag value changes.
* For a generic hook returning a queryable interface, see {@link useFlag}.
* @param {string} flagKey the flag identifier
* @template {number} [T=number] A optional generic argument constraining the number
* @param {T} defaultValue the default value
* @param {ReactFlagEvaluationOptions} options options for this evaluation
* @returns { boolean} a EvaluationDetails object for this evaluation
*/
export function useNumberFlagValue<T extends number = number>(
flagKey: string,
defaultValue: T,
options?: ReactFlagEvaluationOptions,
): number {
return useNumberFlagDetails(flagKey, defaultValue, options).value;
}
/**
* Evaluates a feature flag, returning evaluation details.
* By default, components will re-render when the flag value changes.
* For a generic hook returning a queryable interface, see {@link useFlag}.
* @param {string} flagKey the flag identifier
* @template {number} [T=number] A optional generic argument constraining the number
* @param {T} defaultValue the default value
* @param {ReactFlagEvaluationOptions} options options for this evaluation
* @returns { EvaluationDetails<number>} a EvaluationDetails object for this evaluation
*/
export function useNumberFlagDetails<T extends number = number>(
flagKey: string,
defaultValue: T,
options?: ReactFlagEvaluationOptions,
): EvaluationDetails<number> {
return attachHandlersAndResolve(
flagKey,
defaultValue,
(client) => {
return client.getNumberDetails<T>;
},
options,
);
}
/**
* Evaluates a feature flag, returning an object.
* By default, components will re-render when the flag value changes.
* For a generic hook returning a queryable interface, see {@link useFlag}.
* @param {string} flagKey the flag identifier
* @template {JsonValue} [T=JsonValue] A optional generic argument describing the structure
* @param {T} defaultValue the default value
* @param {ReactFlagEvaluationOptions} options options for this evaluation
* @returns { boolean} a EvaluationDetails object for this evaluation
*/
export function useObjectFlagValue<T extends JsonValue = JsonValue>(
flagKey: string,
defaultValue: T,
options?: ReactFlagEvaluationOptions,
): T {
return useObjectFlagDetails<T>(flagKey, defaultValue, options).value;
}
/**
* Evaluates a feature flag, returning evaluation details.
* By default, components will re-render when the flag value changes.
* For a generic hook returning a queryable interface, see {@link useFlag}.
* @param {string} flagKey the flag identifier
* @param {T} defaultValue the default value
* @template {JsonValue} [T=JsonValue] A optional generic argument describing the structure
* @param {ReactFlagEvaluationOptions} options options for this evaluation
* @returns { EvaluationDetails<T>} a EvaluationDetails object for this evaluation
*/
export function useObjectFlagDetails<T extends JsonValue = JsonValue>(
flagKey: string,
defaultValue: T,
options?: ReactFlagEvaluationOptions,
): EvaluationDetails<T> {
return attachHandlersAndResolve(
flagKey,
defaultValue,
(client) => {
return client.getObjectDetails<T>;
},
options,
);
}
// determines if a flag should be re-evaluated based on a list of changed flags
function shouldEvaluateFlag(flagKey: string, flagsChanged?: string[]): boolean {
// if flagsChange is missing entirely, we don't know what to re-render
return !flagsChanged || flagsChanged.includes(flagKey);
}
function attachHandlersAndResolve<T extends FlagValue>(
flagKey: string,
defaultValue: T,
resolver: (
client: Client,
) => (flagKey: string, defaultValue: T, options?: FlagEvaluationOptions) => EvaluationDetails<T>,
options?: ReactFlagEvaluationOptions,
): EvaluationDetails<T> {
// highest priority > evaluation hook options > provider options > default options > lowest priority
const defaultedOptions = { ...DEFAULT_OPTIONS, ...useProviderOptions(), ...normalizeOptions(options) };
const client = useOpenFeatureClient();
const status = useOpenFeatureClientStatus();
const provider = useOpenFeatureProvider();
const controller = new AbortController();
if (defaultedOptions.suspendUntilReady && status === ProviderStatus.NOT_READY) {
suspendUntilInitialized(provider, client);
}
if (defaultedOptions.suspendWhileReconciling && status === ProviderStatus.RECONCILING) {
suspendUntilReconciled(client);
}
const [evaluationDetails, setEvaluationDetails] = useState<EvaluationDetails<T>>(
resolver(client).call(client, flagKey, defaultValue, options),
);
// Maintain a mutable reference to the evaluation details to have a up-to-date reference in the handlers.
const evaluationDetailsRef = useRef<EvaluationDetails<T>>(evaluationDetails);
useEffect(() => {
evaluationDetailsRef.current = evaluationDetails;
}, [evaluationDetails]);
const updateEvaluationDetailsCallback = () => {
const updatedEvaluationDetails = resolver(client).call(client, flagKey, defaultValue, options);
/**
* Avoid re-rendering if the value hasn't changed. We could expose a means
* to define a custom comparison function if users require a more
* sophisticated comparison in the future.
*/
if (!isEqual(updatedEvaluationDetails.value, evaluationDetailsRef.current.value)) {
setEvaluationDetails(updatedEvaluationDetails);
}
};
const configurationChangeCallback: EventHandler<ClientProviderEvents.ConfigurationChanged> = (eventDetails) => {
if (shouldEvaluateFlag(flagKey, eventDetails?.flagsChanged)) {
updateEvaluationDetailsCallback();
}
};
useEffect(() => {
if (status === ProviderStatus.NOT_READY) {
// update when the provider is ready
client.addHandler(ProviderEvents.Ready, updateEvaluationDetailsCallback, { signal: controller.signal });
}
if (defaultedOptions.updateOnContextChanged) {
// update when the context changes
client.addHandler(ProviderEvents.ContextChanged, updateEvaluationDetailsCallback, { signal: controller.signal });
}
if (defaultedOptions.updateOnConfigurationChanged) {
// update when the provider configuration changes
client.addHandler(ProviderEvents.ConfigurationChanged, configurationChangeCallback, {
signal: controller.signal,
});
}
return () => {
// cleanup the handlers
controller.abort();
};
}, []);
return evaluationDetails;
}