-
-
Notifications
You must be signed in to change notification settings - Fork 24
/
context.js
122 lines (93 loc) · 2.21 KB
/
context.js
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
import { isNone } from '@ember/utils';
import { TrackedMap } from 'tracked-maps-and-sets';
const STORAGE_KEY = 'ember-launch-darkly';
function setPersistedFlags(context) {
let persistedFlags = window.localStorage.getItem(STORAGE_KEY);
if (persistedFlags) {
context.replaceFlags(JSON.parse(persistedFlags));
}
}
function setCurrentContext(context) {
setPersistedFlags(context);
window.__LD__ = context;
}
function getCurrentContext() {
let context = window.__LD__;
if (!context) {
throw new Error(
'Launch Darkly has not been initialized. Ensure that you run the `initialize` function before `variation`.'
);
}
return context;
}
function removeCurrentContext() {
delete window.__LD__;
}
class Context {
_flags = new TrackedMap();
_client = null;
constructor(flags = {}, client) {
this._client = client;
this.updateFlags(flags);
}
updateFlags(flags) {
for (let [key, value] of Object.entries(flags)) {
this._flags.set(key, value);
}
}
replaceFlags(flags) {
this._flags.clear();
this.updateFlags(flags);
}
enable(key) {
this._flags.set(key, true);
}
disable(key) {
this._flags.set(key, false);
}
set(key, value) {
this._flags.set(key, value);
}
get(key, defaultValue) {
if (!this._flags.has(key) && !isNone(defaultValue)) {
return defaultValue;
}
return this._flags.get(key);
}
persist() {
window.localStorage.setItem(STORAGE_KEY, JSON.stringify(this.allFlags));
}
resetPersistence() {
window.localStorage.removeItem(STORAGE_KEY);
}
get allFlags() {
let allFlags = {};
for (let [key, value] of this._flags.entries()) {
allFlags[key] = value;
}
return allFlags;
}
get isLocal() {
return isNone(this.client);
}
get persisted() {
let persisted = window.localStorage.getItem(STORAGE_KEY);
return persisted ? JSON.parse(persisted) : undefined;
}
get client() {
return this._client;
}
get user() {
if (this.isLocal) {
return { key: 'local-mode-no-user-specified' };
}
return this.client.getUser();
}
}
export {
getCurrentContext,
removeCurrentContext,
setCurrentContext,
setPersistedFlags,
Context as default,
};