Skip to content

Commit

Permalink
Merge pull request #15 from bbc/swr-refresh
Browse files Browse the repository at this point in the history
Task: do not cache 5xx for SWR
  • Loading branch information
cejast authored May 14, 2018
2 parents 5eb8624 + 84e5e27 commit a9fb8d1
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
4 changes: 4 additions & 0 deletions lib/maxAge.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,10 @@ function revalidate(cached, url, cache, opts) {

bluebird.resolve(refresh(url))
.then((res) => {
if (res.statusCode >= 500) {
throw new Error(`Failed to refresh ${url}, got status ${res.statusCode}`);
}

storeInCache(cache, SEGMENT, url, res.toJSON(), getMaxAge(res));
})
.catch(() => { })
Expand Down
32 changes: 32 additions & 0 deletions test/maxAge.js
Original file line number Diff line number Diff line change
Expand Up @@ -304,6 +304,38 @@ describe('Max-Age', () => {
assert.equal(cached.item.body, 'We ALL love jonty');
});

it('does not update cache for failed requests', async () => {
const cache = createCache();
const refreshClient = httpTransport.createClient();

const maxage = 1;
const swr = maxage * 2;
const responseHeaders = { 'cache-control': `max-age=${maxage},stale-while-revalidate=${swr}` };

api
.get('/')
.reply(200, 'First Response', responseHeaders);

api
.get('/')
.reply(500, 'Second Response', responseHeaders);

const opts = {
'staleWhileRevalidate': true,
refresh: () => {
return refreshClient.get('http://www.example.com/').asResponse();
}
};

await requestWithCache(cache, opts);
await bluebird.delay((maxage * 1000));
await requestWithCache(cache, opts);
await bluebird.delay(100);

const cached = await cache.get(bodySegment);
assert.equal(cached.item.body, 'First Response');
});

it('does not revalidate for PUT requests', async () => {
assertGetOnly('put');
});
Expand Down

0 comments on commit a9fb8d1

Please sign in to comment.