Skip to content

Commit

Permalink
Return cached response immediately if not stale
Browse files Browse the repository at this point in the history
  • Loading branch information
lukechilds committed May 4, 2017
1 parent 403c1b5 commit fccafe0
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 1 deletion.
22 changes: 21 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ const isRetryAllowed = require('is-retry-allowed');
const Buffer = require('safe-buffer').Buffer;
const expired = require('expired');
const normalizeUrl = require('normalize-url');
const Response = require('http-response-object');
const pkg = require('./package');

function requestAsEventEmitter(opts) {
Expand Down Expand Up @@ -99,7 +100,22 @@ function requestAsEventEmitter(opts) {
});
};

get(opts);
if (opts.cache && opts.method === 'GET') {
const key = normalizeUrl(requestUrl);
opts.cache.get(key, (err, value) => {
if (err) {
return get(opts);
}
const cachedResponse = JSON.parse(value);
if (expired(cachedResponse.headers) === false) {
const response = responseFromCache(requestUrl, cachedResponse);
ee.emit('response', response);
}
});
} else {
get(opts);
}

return ee;
}

Expand Down Expand Up @@ -315,6 +331,10 @@ function normalizeArguments(url, opts) {
return opts;
}

function responseFromCache(url, cachedResponse) {
return new Response(200, cachedResponse.headers, Buffer.from(cachedResponse.body), url);
}

function got(url, opts) {
try {
return asPromise(normalizeArguments(url, opts));
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@
"duplexer3": "^0.1.4",
"expired": "^1.3.8",
"get-stream": "^3.0.0",
"http-response-object": "^1.1.0",
"is-redirect": "^1.0.0",
"is-retry-allowed": "^1.0.0",
"is-stream": "^1.0.0",
Expand Down

0 comments on commit fccafe0

Please sign in to comment.