-
Notifications
You must be signed in to change notification settings - Fork 0
/
eppo-client.ts
66 lines (61 loc) · 2.13 KB
/
eppo-client.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
import type { Attributes } from '@eppo/js-client-sdk-common';
import { init } from '@eppo/node-server-sdk';
import {
EppoExperimentFieldsFragment,
PageBlogPostFieldsFragment,
RichImageFieldsFragment,
} from '@src/lib/__generated/sdk';
/**
* For this example, we'll assume that our "Eppo Experiment" can accept
* "component - Rich image" or "page - Blog post" for use in variations.
* This can be updated in src/lib/graphql/eppoExperimentFields.graphql.
*/
export type VariationEntry = RichImageFieldsFragment | PageBlogPostFieldsFragment;
const eppoClientPromise = (() => {
if (!process.env.EPPO_SDK_KEY) {
throw new Error('Missing EPPO_SDK_KEY environment variable');
}
return init({
apiKey: process.env.EPPO_SDK_KEY,
baseUrl: process.env.EPPO_BASE_URL_OVERRIDE || undefined,
assignmentLogger: {
logAssignment(assignment) {
console.log('EppoClient.assignmentLogger => logAssignment()', assignment);
},
},
});
})();
async function getEppoClient() {
return await eppoClientPromise;
}
export async function selectExperimentEntry<T extends VariationEntry>(
eppoExperiment: EppoExperimentFieldsFragment | null | undefined,
subjectKey: string,
subjectAttributes: Attributes = {},
): Promise<T | null> {
if (!eppoExperiment) {
return null;
}
const flagKey = eppoExperiment.flagKey;
if (!flagKey) {
throw new Error(`missing required flagKey for entry ${eppoExperiment.sys.id}`);
}
const controlVariationEntry = eppoExperiment.controlVariation as T;
if (!controlVariationEntry) {
throw new Error(`missing required controlVariation for entry ${eppoExperiment.sys.id}`);
}
const treatmentVariationEntries = (eppoExperiment.treatmentVariationsCollection?.items ??
[]) as Array<T>;
if (!treatmentVariationEntries.length) {
throw new Error(
`missing required treatmentVariationsCollection for entry ${eppoExperiment.sys.id}`,
);
}
const eppoClient = await getEppoClient();
const experiment = {
flagKey,
controlVariationEntry,
treatmentVariationEntries,
};
return eppoClient.getExperimentContainerEntry(experiment, subjectKey, subjectAttributes);
}