Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add metadata if response came from cache #371

Merged
merged 5 commits into from
Nov 19, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/long-experts-chew.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@apollo/datasource-rest': minor
---

Add metadata if response came from cache
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
"test:ci": "jest --coverage --ci --maxWorkers=2 --reporters=default --reporters=jest-junit",
"watch": "tsc --build --watch",
"lint": "eslint src/**/*.ts",
"changeset-add": "changeset add",
"changeset-publish": "changeset publish",
"changeset-check": "changeset status --verbose --since=origin/main"
},
Expand Down
7 changes: 6 additions & 1 deletion src/HTTPCache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ interface SneakyCachePolicy extends CachePolicy {

interface ResponseWithCacheWritePromise {
response: FetcherResponse;
responseFromCache?: Boolean;
cacheWritePromise?: Promise<void>;
}

Expand Down Expand Up @@ -72,7 +73,10 @@ export class HTTPCache<CO extends CacheOptions = CacheOptions> {
// refreshing headers with HEAD requests, responding to HEADs with cached
// and valid GETs, etc.)
if (requestOpts.method === 'HEAD') {
return { response: await this.httpFetch(urlString, requestOpts) };
return {
response: await this.httpFetch(urlString, requestOpts),
responseFromCache: false,
};
}

const entry =
Expand Down Expand Up @@ -127,6 +131,7 @@ export class HTTPCache<CO extends CacheOptions = CacheOptions> {
status: policy._status,
headers: cachePolicyHeadersToNodeFetchHeadersInit(headers),
}),
responseFromCache: true,
};
} else {
// We aren't sure that we're allowed to use the cached response, so we are
Expand Down
10 changes: 7 additions & 3 deletions src/__tests__/HTTPCache.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,10 +63,12 @@ describe('HTTPCache', () => {
it('fetches a response from the origin when not cached', async () => {
mockGetAdaLovelace();

const { response, cacheWritePromise } = await httpCache.fetch(adaUrl);
const { response, responseFromCache, cacheWritePromise } =
await httpCache.fetch(adaUrl);
expect(cacheWritePromise).toBeUndefined();

expect(await response.json()).toEqual({ name: 'Ada Lovelace' });
expect(responseFromCache).toBeFalsy();
});

it('returns a cached response when not expired', async () => {
Expand All @@ -79,11 +81,12 @@ describe('HTTPCache', () => {
await cacheWritePromise;
jest.advanceTimersByTime(10000);

const { response } = await httpCache.fetch(adaUrl);
const { response, responseFromCache } = await httpCache.fetch(adaUrl);

expect(response.url).toBe(adaUrl.toString());
expect(await response.json()).toEqual({ name: 'Ada Lovelace' });
expect(response.headers.get('age')).toEqual('10');
expect(responseFromCache).toBe(true);
});

it('fetches a fresh response from the origin when expired', async () => {
Expand All @@ -96,12 +99,13 @@ describe('HTTPCache', () => {

mockGetAlanTuring({ 'cache-control': 'max-age=30' });

const { response } = await httpCache.fetch(
const { response, responseFromCache } = await httpCache.fetch(
new URL('https://api.example.com/people/1'),
);

expect(await response.json()).toEqual({ name: 'Alan Turing' });
expect(response.headers.get('age')).toBeNull();
expect(responseFromCache).toBeFalsy();
});

describe('overriding TTL', () => {
Expand Down