-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathflag.ts
41 lines (36 loc) · 1.05 KB
/
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
import { evaluateFlags } from "./evaluateFlags";
import { flagsClient } from "./flagsClient";
import { getDefinitions } from "./getDefinitions";
import type { IVariant } from "unleash-proxy-client";
import type { Context } from "unleash-client";
export const flag = async <T extends string, V extends Partial<IVariant>>(
flag: T,
context: Context = {},
options?: Parameters<typeof getDefinitions>[0]
) => {
const revalidate =
options?.fetchOptions?.next?.revalidate !== undefined
? options?.fetchOptions?.next?.revalidate
: 15;
try {
const definitions = await getDefinitions({
...options,
fetchOptions: {
next: { revalidate },
...options?.fetchOptions,
},
});
const { toggles } = await evaluateFlags(definitions, context);
const client = flagsClient(toggles);
return {
enabled: client.isEnabled(flag),
variant: client.getVariant(flag) as V,
};
} catch (error: unknown) {
return {
enabled: false,
variant: {} as Partial<IVariant>,
error,
};
}
};