-
Notifications
You must be signed in to change notification settings - Fork 51
/
Copy pathflagsmith-client-provider.ts
160 lines (144 loc) · 4.79 KB
/
flagsmith-client-provider.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
import {
EvaluationContext,
FlagValue,
JsonValue,
Logger,
OpenFeatureEventEmitter,
Provider,
ProviderEvents,
ProviderMetadata,
ResolutionDetails,
ResolutionReason,
TypeMismatchError,
} from '@openfeature/web-sdk';
import { createFlagsmithInstance } from 'flagsmith';
import { IFlagsmith, IInitConfig, IState } from 'flagsmith/types';
import { FlagType, typeFactory } from './type-factory';
export class FlagsmithClientProvider implements Provider {
readonly metadata: ProviderMetadata = {
name: FlagsmithClientProvider.name,
};
readonly runsOn = 'client';
//The Flagsmith Client
private _client: IFlagsmith;
//The Open Feature logger to use
private _logger?: Logger;
//The configuration used for the Flagsmith SDK
private _config: IInitConfig;
// The Open Feature event emitter
events = new OpenFeatureEventEmitter();
constructor({
logger,
flagsmithInstance,
...config
}: Omit<IInitConfig, 'identity' | 'traits'> & { logger?: Logger; flagsmithInstance?: IFlagsmith }) {
this._logger = logger;
this._client = flagsmithInstance || createFlagsmithInstance();
this._config = config;
}
async initialize(context?: EvaluationContext & Partial<IState>) {
const identity = context?.targetingKey;
if (this._client?.initialised) {
//Already initialised, set the state based on the new context, allow certain context props to be optional
const defaultState = { ...this._client.getState(), identity: undefined, traits: {} };
const isLogout = !!this._client.identity && !identity;
this._client.identity = identity;
this._client.setState({
...defaultState,
...(context || {}),
});
this.events.emit(ProviderEvents.Stale, { message: 'context has changed' });
return isLogout ? this._client.logout() : this._client.getFlags();
}
const serverState = this._config.state;
if (serverState) {
this._client.setState(serverState);
this.events.emit(ProviderEvents.Ready, { message: 'flags provided by SSR state' });
}
return this._client.init({
...this._config,
...context,
identity,
onChange: (previousFlags, params, loadingState) => {
const eventMeta = {
metadata: this.getMetadata(),
flagsChanged: params.flagsChanged,
};
this.events.emit(ProviderEvents.Ready, {
message: 'Flags ready',
...eventMeta,
});
if (params.flagsChanged) {
this.events.emit(ProviderEvents.ConfigurationChanged, {
message: 'Flags changed',
...eventMeta,
});
}
this._config.onChange?.(previousFlags, params, loadingState);
},
});
}
onContextChange(oldContext: EvaluationContext, newContext: EvaluationContext & Partial<IState>) {
this.events.emit(ProviderEvents.Stale, { message: 'Context Changed' });
return this.initialize(newContext);
}
resolveBooleanEvaluation(flagKey: string) {
return this.evaluate<boolean>(flagKey, 'boolean', false);
}
resolveStringEvaluation(flagKey: string, defaultValue: string) {
return this.evaluate<string>(flagKey, 'string', defaultValue);
}
resolveNumberEvaluation(flagKey: string, defaultValue: number) {
return this.evaluate<number>(flagKey, 'number', defaultValue);
}
resolveObjectEvaluation<T extends JsonValue>(flagKey: string, defaultValue: T) {
return this.evaluate<T>(flagKey, 'object', defaultValue);
}
/**
* Based on Flagsmith's state, return flag metadata
* @private
*/
private getMetadata() {
return {
targetingKey: this._client.identity || '',
...(this._client.getAllTraits() || {}),
};
}
/**
* Based on Flagsmith's loading state, determine the Open Feature resolution reason
* @private
*/
private evaluate<T extends FlagValue>(flagKey: string, type: FlagType, defaultValue: T) {
const value = typeFactory(
type === 'boolean' ? this._client.hasFeature(flagKey) : this._client.getValue(flagKey),
type,
);
if (typeof value !== 'undefined' && typeof value !== type) {
throw new TypeMismatchError(`flag key ${flagKey} is not of type ${type}`);
}
return {
value: (typeof value !== type ? defaultValue : value) as T,
reason: this.parseReason(value),
} as ResolutionDetails<T>;
}
/**
* Based on Flagsmith's loading state and feature resolution, determine the Open Feature resolution reason
* @private
*/
private parseReason(value: unknown): ResolutionReason {
if (value === undefined) {
return 'DEFAULT';
}
switch (this._client.loadingState?.source) {
case 'CACHE':
return 'CACHED';
case 'DEFAULT_FLAGS':
return 'DEFAULT';
default:
return 'STATIC';
}
}
public get flagsmithClient() {
return this._client;
}
}