Skip to content

Commit

Permalink
feat: add served from response cache symbol to response cache (#3164)
Browse files Browse the repository at this point in the history
  • Loading branch information
n1ru4l authored Jan 16, 2024
1 parent e65b273 commit 353c0fe
Show file tree
Hide file tree
Showing 3 changed files with 76 additions and 2 deletions.
7 changes: 7 additions & 0 deletions .changeset/big-tables-clean.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
'@graphql-yoga/plugin-response-cache': minor
---

Add `servedFromResponseCache` symbol property to responses served from the response cache in order
to allow other plugins to determine, whether a response was served from the cache and apply custom
logic based on that.
63 changes: 63 additions & 0 deletions packages/plugins/response-cache/__tests__/response-cache.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1152,3 +1152,66 @@ describe('shouldCacheResult', () => {
});
});
});

it('response has "servedFromResponseCache" symbol', async () => {
const results: Array<any> = [];
const yoga = createYoga({
plugins: [
useResponseCache({
session: () => null,
includeExtensionMetadata: true,
}),
{
onResultProcess(context) {
results.push(context.result);
},
},
],
schema,
});
function fetch() {
return yoga.fetch('http://localhost:3000/graphql', {
method: 'POST',
headers: {
'content-type': 'application/json',
},
body: JSON.stringify({ query: '{__typename}' }),
});
}

let response = await fetch();

expect(response.status).toEqual(200);
let body = await response.json();
expect(body).toEqual({
data: {
__typename: 'Query',
},
extensions: {
responseCache: {
didCache: true,
hit: false,
ttl: null,
},
},
});

response = await fetch();
expect(response.status).toEqual(200);
body = await response.json();
expect(body).toMatchObject({
data: {
__typename: 'Query',
},
extensions: {
responseCache: {
hit: true,
},
},
});

const [result1, result2] = results;
expect(Symbol.for('servedFromResponseCache') in result1).toEqual(false);
expect(Symbol.for('servedFromResponseCache') in result2).toEqual(true);
expect(result2[Symbol.for('servedFromResponseCache')]).toEqual(true);
});
8 changes: 6 additions & 2 deletions packages/plugins/response-cache/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -170,10 +170,14 @@ export function useResponseCache(options: UseResponseCacheParameter): Plugin {
if (enabled(request)) {
const cachedResponse = await cache.get(operationId);
if (cachedResponse) {
const responseWithSymbol = {
...cachedResponse,
[Symbol.for('servedFromResponseCache')]: true,
};
if (options.includeExtensionMetadata) {
setResult(resultWithMetadata(cachedResponse, { hit: true }));
setResult(resultWithMetadata(responseWithSymbol, { hit: true }));
} else {
setResult(cachedResponse);
setResult(responseWithSymbol);
}
return;
}
Expand Down

0 comments on commit 353c0fe

Please sign in to comment.