Skip to content

Commit

Permalink
Optional response caching
Browse files Browse the repository at this point in the history
  • Loading branch information
lukechilds committed May 4, 2017
1 parent a5f2730 commit 403c1b5
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 0 deletions.
17 changes: 17 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ const unzipResponse = require('unzip-response');
const createErrorClass = require('create-error-class');
const isRetryAllowed = require('is-retry-allowed');
const Buffer = require('safe-buffer').Buffer;
const expired = require('expired');
const normalizeUrl = require('normalize-url');
const pkg = require('./package');

function requestAsEventEmitter(opts) {
Expand Down Expand Up @@ -58,6 +60,21 @@ function requestAsEventEmitter(opts) {
response.url = redirectUrl || requestUrl;
response.requestUrl = requestUrl;

if (opts.cache && statusCode === 200 && req.method === 'GET' && (expired(response.headers) === false || 'etag' in response.headers)) {
const encoding = opts.encoding === null ? 'buffer' : opts.encoding;
const stream = getStream(stream, {encoding});

stream
.then(data => {
const key = normalizeUrl(response.url);
const value = JSON.stringify({
headers: response.headers,
body: data
});
opts.cache.put(key, value);
});
}

ee.emit('response', response);
});
});
Expand Down
2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -44,11 +44,13 @@
"dependencies": {
"create-error-class": "^3.0.0",
"duplexer3": "^0.1.4",
"expired": "^1.3.8",
"get-stream": "^3.0.0",
"is-redirect": "^1.0.0",
"is-retry-allowed": "^1.0.0",
"is-stream": "^1.0.0",
"lowercase-keys": "^1.0.0",
"normalize-url": "^1.9.1",
"safe-buffer": "^5.0.1",
"timed-out": "^4.0.0",
"unzip-response": "^2.0.1",
Expand Down

0 comments on commit 403c1b5

Please sign in to comment.