-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathconfigcache.mjs
63 lines (55 loc) · 2.24 KB
/
configcache.mjs
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
import * as _ from 'lodash-es';
const cache = {};
let cacheFirebase;
export const setCacheFirebase = (firebase) => cacheFirebase = firebase;
// To be called to indicate an endpoint has changes and any resources should be purged
let invalidationCallback = (namespace, baseURL) => {}
export const setInvalidationCallback = (callback) => invalidationCallback = callback;
// For config defined in notebooks
export const setNotebook = async (endpointURL, config) => cache[endpointURL] = config;
export const getNotebook = async (endpointURL) => cache[endpointURL];
export const get = async (endpointURL) => {
const dynamic = await getDynamic(endpointURL);
const notebook = await getNotebook(endpointURL);
if (dynamic === undefined && notebook === undefined) {
return undefined;
}
return _.mergeWith(_.cloneDeep(dynamic), notebook, (objValue, srcValue) => {
if (_.isArray(objValue)) {
return objValue.concat(srcValue);
}
});
}
// For config defined in Firestore
const cacheFirestore = {};
export const getDynamic = async (endpointURL) => {
endpointURL = endpointURL.substring(1);
if (endpointURL in cacheFirestore) return cacheFirestore[endpointURL];
else {
console.log(`Subscribing to config for ${endpointURL}`)
// create subscription to watch for changes
const firestore = cacheFirebase.firestore();
const configDoc = firestore.doc(
`/services/http/endpoints/${encodeURIComponent(endpointURL)}`
);
let hasResolved = false;
cacheFirestore[endpointURL] = new Promise(resolve => {
// update cache on change
configDoc.onSnapshot(snap => {
const record = snap.data();
cacheFirestore[endpointURL] = record && {
modifiers: [],
reusable: true,
...record,
secrets: Object.keys(record.secrets || {})
};
if (record) invalidationCallback(record.namespace, endpointURL);
if (!hasResolved) {
hasResolved = true;
resolve(cacheFirestore[endpointURL]);
}
})
});
}
return cacheFirestore[endpointURL];
}