UNPKG

@graphql-yoga/plugin-response-cache

Version:

For the documentation check `http://graphql-yoga.com/docs/response-cache`

50 lines (49 loc) 2.07 kB
import { createInMemoryCache, defaultBuildResponseCacheKey, useResponseCache as useEnvelopResponseCache, } from '@envelop/response-cache'; const operationIdByRequest = new WeakMap(); // We trick Envelop plugin by passing operationId as sessionId so we can take it from cache key builder we pass to Envelop function sessionFactoryForEnvelop({ request }) { return operationIdByRequest.get(request); } export function useResponseCache(options) { const buildResponseCacheKey = options?.buildResponseCacheKey || defaultBuildResponseCacheKey; const cache = options.cache ?? createInMemoryCache(); const enabled = options.enabled ?? (() => true); return { onPluginInit({ addPlugin }) { addPlugin(useEnvelopResponseCache({ ...options, cache, session: sessionFactoryForEnvelop, })); }, async onParams({ params, request, setResult }) { if (enabled(request)) { const operationId = await buildResponseCacheKey({ documentString: params.query, variableValues: params.variables, operationName: params.operationName, sessionId: await options.session(request), }); const cachedResponse = await cache.get(operationId); if (cachedResponse) { if (options.includeExtensionMetadata) { setResult({ ...cachedResponse, extensions: { responseCache: { hit: true, }, }, }); } else { setResult(cachedResponse); } return; } operationIdByRequest.set(request, operationId); } }, }; } export { createInMemoryCache };