-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcreateDataCache.mjs
More file actions
70 lines (65 loc) · 1.79 KB
/
createDataCache.mjs
File metadata and controls
70 lines (65 loc) · 1.79 KB
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
import createSubscription from "./createSubscription.mjs";
import dataLoader from "./dataLoader.mjs";
const defaultOptions = { maxEntries: 10000 };
/**
* Creates a data cache.
* @kind function
* @name createDataCache
* @param {object} userOptions User configurable options.
* @prop {number} maxEntries The maximum allowed cache entries before old entries are dropped.
* @returns {DataCache} A dataCache object.
*/
export default function createDataCache(userOptions = defaultOptions) {
const options = {
...defaultOptions,
...userOptions,
};
const subscription = createSubscription();
const dataCache = {
cache: new Map(),
get(key) {
return dataCache.cache.get(key);
},
set(key, reference) {
dataCache.cache.set(key, reference);
if (dataCache.cache.size > options.maxEntries) {
for (const [key] of dataCache.cache) {
dataCache.cache.delete(key);
break;
}
}
},
preload(key, asyncFn) {
return new Promise((resolve) => {
if (dataCache.get(key)) {
return resolve(dataCache.get(key).value);
}
dataCache.load(key, asyncFn).then(resolve);
});
},
load(key, asyncFn) {
return new Promise((resolve) => {
dataLoader(key, asyncFn, dataCache).load((reference) => {
resolve(reference.value);
});
});
},
find(predicateOrKey) {
for (const reference of dataCache.values()) {
if (
(typeof predicateOrKey === "function" &&
predicateOrKey(reference.key)) ||
predicateOrKey === reference.key
) {
return reference;
}
}
},
subscription,
onUpdate: subscription.subscribe,
reset() {
dataCache.cache = new Map();
},
};
return dataCache;
}