diff --git a/src/edge/edge-init.ts b/src/edge/edge-init.ts new file mode 100644 index 0000000..a13c277 --- /dev/null +++ b/src/edge/edge-init.ts @@ -0,0 +1,48 @@ +import { applicationLogger } from '..'; +import ApiEndpoints from '../api-endpoints'; +import { DEFAULT_REQUEST_TIMEOUT_MS } from '../constants'; +import FetchHttpClient from '../http-client'; +import { Variation } from '../interfaces'; +import { AttributeType } from '../types'; + +import { EppoClientEdge } from './eppo-client-edge'; + +type VariationValue = Variation['value'] | object; + +export interface IEdgeConfig { + apiKey: string; + subjectKey: string; + subjectAttributes: Record; + throwOnFailedInitialization?: boolean; + baseUrl?: string; +} + +export async function commonEdgeInit( + config: IEdgeConfig, + sdkName: string, + sdkVersion: string, +): Promise { + const { apiKey, baseUrl, throwOnFailedInitialization } = config; + try { + const apiEndpoints = new ApiEndpoints({ + baseUrl, + queryParams: { apiKey, sdkName, sdkVersion }, + }); + const httpClient = new FetchHttpClient(apiEndpoints, DEFAULT_REQUEST_TIMEOUT_MS); + const assignments = await httpClient.rawGet>( + apiEndpoints.endpoint('/flag-config/v1/edge-config'), + ); + if (!assignments) { + throw new Error('Unable to get assignments'); + } + return new EppoClientEdge(assignments); + } catch (error) { + applicationLogger.warn( + 'Eppo SDK encountered an error initializing, assignment calls will return the default value', + ); + if (throwOnFailedInitialization) { + throw error; + } + return new EppoClientEdge({}); + } +} diff --git a/src/edge/eppo-client-edge.ts b/src/edge/eppo-client-edge.ts new file mode 100644 index 0000000..21f849a --- /dev/null +++ b/src/edge/eppo-client-edge.ts @@ -0,0 +1,39 @@ +import { Variation } from '../interfaces'; + +type VariationValue = Variation['value'] | object; + +export class EppoClientEdge { + constructor(private cachedAssignments: Record) {} + + getAssignments() { + return this.cachedAssignments; + } + + getStringAssignment(flagKey: string, defaultValue: string): string { + if (typeof this.cachedAssignments[flagKey] === 'string') { + return this.cachedAssignments[flagKey]; + } + return defaultValue; + } + + getBooleanAssignment(flagKey: string, defaultValue: boolean): boolean { + if (typeof this.cachedAssignments[flagKey] === 'boolean') { + return this.cachedAssignments[flagKey]; + } + return defaultValue; + } + + getNumericAssignment(flagKey: string, defaultValue: number): number { + if (typeof this.cachedAssignments[flagKey] === 'number') { + return this.cachedAssignments[flagKey]; + } + return defaultValue; + } + + getJSONAssignment(flagKey: string, defaultValue: object): object { + if (typeof this.cachedAssignments[flagKey] === 'object') { + return this.cachedAssignments[flagKey]; + } + return defaultValue; + } +}