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 Dynamic Prefix To Cache Key #6428

Closed
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
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,12 @@ interface Options<TContext = Record<string, any>> {
requestContext: GraphQLRequestContext<TContext>,
): ValueOrPromise<any>;

// Define this hook if you want the cache key to use a prefix before the hash
// Example: {operationName}:{keyHash}
dynamicPrefix?(
requestContext: GraphQLRequestContext<TContext>,
): ValueOrPromise<string>;

// If this hook is defined and returns false, the plugin will not read
// responses from the cache.
shouldReadFromCache?(
Expand Down Expand Up @@ -133,6 +139,8 @@ function isGraphQLQuery(requestContext: GraphQLRequestContext<any>) {
return requestContext.operation?.operation === 'query';
}

let dynamicPrefix: string = '';

export default function plugin(
options: Options = Object.create(null),
): ApolloServerPlugin {
Expand Down Expand Up @@ -166,7 +174,7 @@ export default function plugin(
...baseCacheKey!,
...contextualCacheKeyFields,
});
const serializedValue = await cache.get(key);
const serializedValue = await cache.get(dynamicPrefix + key);
if (serializedValue === undefined) {
return null;
}
Expand All @@ -189,6 +197,10 @@ export default function plugin(
extraCacheKeyData = await options.extraCacheKeyData(requestContext);
}

if (options.dynamicPrefix) {
dynamicPrefix = await options.dynamicPrefix(requestContext);
}

baseCacheKey = {
source: requestContext.source!,
operationName: requestContext.operationName,
Expand Down Expand Up @@ -293,7 +305,9 @@ export default function plugin(
// still calls `cache.set` synchronously (ie, that it writes to
// InMemoryLRUCache synchronously).
cache
.set(key, serializedValue, { ttl: policyIfCacheable.maxAge })
.set(dynamicPrefix + key, serializedValue, {
ttl: policyIfCacheable.maxAge,
})
.catch(logger.warn);
};

Expand Down