feat: Add error handling for inMemoryCache
This commit is contained in:
committed by
mrugesh mohapatra
parent
09cb38aa21
commit
15a9992603
@ -2,21 +2,32 @@ function isPromiseLike(thing) {
|
||||
return !!thing && typeof thing.then === 'function';
|
||||
}
|
||||
|
||||
function InMemoryCache(initialValue) {
|
||||
function InMemoryCache(initialValue, reportError) {
|
||||
if (typeof reportError !== 'function') {
|
||||
throw new Error(
|
||||
'No reportError function specified for this in-memory-cache'
|
||||
);
|
||||
}
|
||||
const cacheKey = Symbol('cacheKey');
|
||||
const cache = new Map();
|
||||
|
||||
if (typeof initialValue !== 'undefined') {
|
||||
cache.set(cacheKey, initialValue);
|
||||
}
|
||||
cache.set(cacheKey, initialValue);
|
||||
|
||||
return {
|
||||
get() {
|
||||
const value = cache.get(cacheKey);
|
||||
return typeof value !== 'undefined' ? value : null;
|
||||
},
|
||||
|
||||
async update(fn) {
|
||||
const maybePromisedValue = fn();
|
||||
let maybePromisedValue;
|
||||
try {
|
||||
maybePromisedValue = fn();
|
||||
} catch (e) {
|
||||
const errMsg = `InMemoryCache > update > caught: ${e.message}`;
|
||||
e.message = errMsg;
|
||||
reportError(e);
|
||||
return null;
|
||||
}
|
||||
if (isPromiseLike(maybePromisedValue)) {
|
||||
return maybePromisedValue.then(value => cache.set(cacheKey, value));
|
||||
} else {
|
||||
@ -25,6 +36,7 @@ function InMemoryCache(initialValue) {
|
||||
return null;
|
||||
}
|
||||
},
|
||||
|
||||
clear() {
|
||||
return cache.delete(cacheKey);
|
||||
}
|
||||
|
Reference in New Issue
Block a user