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

✨ Adding generateCacheKey to ApolloServerPluginResponseCache to allow for custom cache keys #6655

Merged
merged 11 commits into from
Jul 11, 2022
1 change: 1 addition & 0 deletions docs/source/performance/caching.md
Original file line number Diff line number Diff line change
Expand Up @@ -472,3 +472,4 @@ In addition to [the `sessionId` function](#identifying-users-for-private-respons
| `extraCacheKeyData` | This function's return value (any JSON-stringifiable object) is added to the key for the cached response. For example, if your API includes translatable text, this function can return a string derived from `requestContext.request.http.headers.get('Accept-Language')`. |
| `shouldReadFromCache` | If this function returns `false`, Apollo Server _skips_ the cache for the incoming operation, even if a valid response is available. |
| `shouldWriteToCache` | If this function returns `false`, Apollo Server doesn't cache its response for the incoming operation, even if the response's `maxAge` is greater than `0`. |
| `generateCacheKey` | This function's return is used as the key for the cache. If it is not overrode a sha256 hash is used |
kschrade marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,10 @@ export default function plugin(
'fqc:',
);

const generateCacheKey = options.generateCacheKey
? options.generateCacheKey
: (_: any, key: any) => sha(JSON.stringify(key));
trevor-scheer marked this conversation as resolved.
Show resolved Hide resolved

let sessionId: string | null = null;
let baseCacheKey: BaseCacheKey | null = null;
let age: number | null = null;
Expand All @@ -177,9 +181,7 @@ export default function plugin(
...contextualCacheKeyFields,
};

const key = options.generateCacheKey
? options.generateCacheKey(requestContext, cacheKeyData)
: cacheKeyString(cacheKeyData);
const key = generateCacheKey(requestContext, cacheKeyData);

const serializedValue = await cache.get(key);
if (serializedValue === undefined) {
Expand Down Expand Up @@ -295,9 +297,7 @@ export default function plugin(
...contextualCacheKeyFields,
};

const key = options.generateCacheKey
? options.generateCacheKey(requestContext, cacheKeyData)
: cacheKeyString(cacheKeyData);
const key = generateCacheKey(requestContext, cacheKeyData);

const value: CacheValue = {
data,
Expand Down