Browse Source

Allow opts.cache.get to return value or Promise

extract-response
Luke Childs 8 years ago
parent
commit
5ec945f527
  1. 31
      index.js

31
index.js

@ -106,21 +106,22 @@ function requestAsEventEmitter(opts) {
if (opts.cache) { if (opts.cache) {
const key = cacheKey(opts); const key = cacheKey(opts);
opts.cache.get(key, (err, value) => { Promise.resolve(opts.cache.get(key))
if (err) { .then(value => {
return get(opts); if (typeof value === 'undefined') {
} throw new TypeError('Cached value is undefined');
const cachedValue = JSON.parse(value); }
const policy = CachePolicy.fromObject(cachedValue.policy); const cachedValue = JSON.parse(value);
if (!policy.satisfiesWithoutRevalidation(opts)) { const policy = CachePolicy.fromObject(cachedValue.policy);
get(opts); if (!policy.satisfiesWithoutRevalidation(opts)) {
opts.cache.del(key); opts.cache.del(key);
return; throw new Error('Cached value is stale');
} }
cachedValue.response.headers = policy.responseHeaders(); cachedValue.response.headers = policy.responseHeaders();
const response = responseFromCache(requestUrl, cachedValue.response); const response = responseFromCache(requestUrl, cachedValue.response);
ee.emit('response', response); ee.emit('response', response);
}); })
.catch(() => get(opts));
} else { } else {
get(opts); get(opts);
} }

Loading…
Cancel
Save