Skip to content

Commit

Permalink
Fix HEAD caching behavior, update tests
Browse files Browse the repository at this point in the history
  • Loading branch information
trevor-scheer committed Dec 9, 2022
1 parent fc82dc5 commit 9d55193
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 9 deletions.
5 changes: 5 additions & 0 deletions src/HTTPCache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,11 @@ export class HTTPCache {
requestOpts.method = requestOpts.method ?? 'GET';
const cacheKey = cache?.cacheKey ?? urlString;

// Bypass the cache altogether for HEAD requests
if (requestOpts.method === 'HEAD') {
return this.httpFetch(urlString, requestOpts);
}

const entry = await this.keyValueCache.get(cacheKey);
if (!entry) {
// There's nothing in our cache. Fetch the URL and save it to the cache if
Expand Down
31 changes: 22 additions & 9 deletions src/__tests__/HTTPCache.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -491,21 +491,34 @@ describe('HTTPCache', () => {
});

describe('HEAD requests', () => {
it('returns a cached GET response when the method is HEAD', async () => {
mockGetAdaLovelace();
it('bypasses the cache', async () => {
// x2
nock(apiUrl).head(adaPath).times(2).reply(200);

await httpCache.fetch(adaUrl, {}, { cacheOptions: { ttl: 30000 } });
await httpCache.fetch(adaUrl, {
method: 'HEAD',
});

const headResponse = await httpCache.fetch(adaUrl, {
await httpCache.fetch(adaUrl, {
method: 'HEAD',
});
});

expect(headResponse.status).toEqual(200);
expect(await headResponse.json()).toMatchInlineSnapshot(`
it('bypasses the cache even with explicit ttl', async () => {
// x2
nock(apiUrl).head(adaPath).times(2).reply(200);

await httpCache.fetch(
adaUrl,
{
"name": "Ada Lovelace",
}
`);
method: 'HEAD',
},
{ cacheOptions: { ttl: 30000 } },
);

await httpCache.fetch(adaUrl, {
method: 'HEAD',
});
});
});
});

0 comments on commit 9d55193

Please sign in to comment.