diff --git a/packages/apollo-server-plugin-response-cache/src/ApolloServerPluginResponseCache.ts b/packages/apollo-server-plugin-response-cache/src/ApolloServerPluginResponseCache.ts index 71da54b6fc4..cce84c14f59 100644 --- a/packages/apollo-server-plugin-response-cache/src/ApolloServerPluginResponseCache.ts +++ b/packages/apollo-server-plugin-response-cache/src/ApolloServerPluginResponseCache.ts @@ -72,6 +72,12 @@ interface Options> { requestContext: GraphQLRequestContext, ): ValueOrPromise; + // Define this hook if you want the cache key to use a prefix before the hash + // Example: {operationName}:{keyHash} + dynamicPrefix?( + requestContext: GraphQLRequestContext, + ): ValueOrPromise; + // If this hook is defined and returns false, the plugin will not read // responses from the cache. shouldReadFromCache?( @@ -133,6 +139,8 @@ function isGraphQLQuery(requestContext: GraphQLRequestContext) { return requestContext.operation?.operation === 'query'; } +let dynamicPrefix: string = ''; + export default function plugin( options: Options = Object.create(null), ): ApolloServerPlugin { @@ -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; } @@ -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, @@ -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); };