2018-12-01 11:21:40 +00:00
|
|
|
function isPromiseLike(thing) {
|
|
|
|
return !!thing && typeof thing.then === 'function';
|
|
|
|
}
|
|
|
|
|
2018-12-02 13:38:03 +00:00
|
|
|
function InMemoryCache(initialValue, reportError) {
|
|
|
|
if (typeof reportError !== 'function') {
|
|
|
|
throw new Error(
|
|
|
|
'No reportError function specified for this in-memory-cache'
|
|
|
|
);
|
|
|
|
}
|
2018-12-01 11:21:40 +00:00
|
|
|
const cacheKey = Symbol('cacheKey');
|
|
|
|
const cache = new Map();
|
2018-12-02 13:38:03 +00:00
|
|
|
cache.set(cacheKey, initialValue);
|
2018-12-01 11:21:40 +00:00
|
|
|
|
|
|
|
return {
|
|
|
|
get() {
|
|
|
|
const value = cache.get(cacheKey);
|
|
|
|
return typeof value !== 'undefined' ? value : null;
|
|
|
|
},
|
2018-12-02 13:38:03 +00:00
|
|
|
|
2018-12-03 10:33:07 +00:00
|
|
|
update(fn) {
|
2018-12-02 13:38:03 +00:00
|
|
|
try {
|
2018-12-03 10:33:07 +00:00
|
|
|
const value = fn();
|
|
|
|
if (isPromiseLike(value)) {
|
|
|
|
return value.then(value => cache.set(cacheKey, value));
|
|
|
|
} else {
|
|
|
|
cache.set(cacheKey, value);
|
|
|
|
}
|
2018-12-02 13:38:03 +00:00
|
|
|
} catch (e) {
|
|
|
|
const errMsg = `InMemoryCache > update > caught: ${e.message}`;
|
|
|
|
e.message = errMsg;
|
|
|
|
reportError(e);
|
2018-12-01 11:21:40 +00:00
|
|
|
}
|
2018-12-03 10:33:07 +00:00
|
|
|
return null;
|
2018-12-01 11:21:40 +00:00
|
|
|
},
|
2018-12-02 13:38:03 +00:00
|
|
|
|
2018-12-01 11:21:40 +00:00
|
|
|
clear() {
|
|
|
|
return cache.delete(cacheKey);
|
|
|
|
}
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
export default InMemoryCache;
|