@graphql-yoga/plugin-response-cache
Version:
For the documentation check `http://graphql-yoga.com/docs/response-cache`
54 lines (53 loc) • 2.34 kB
JavaScript
Object.defineProperty(exports, "__esModule", { value: true });
exports.createInMemoryCache = exports.useResponseCache = void 0;
const response_cache_1 = require("@envelop/response-cache");
Object.defineProperty(exports, "createInMemoryCache", { enumerable: true, get: function () { return response_cache_1.createInMemoryCache; } });
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);
}
function useResponseCache(options) {
const buildResponseCacheKey = options?.buildResponseCacheKey || response_cache_1.defaultBuildResponseCacheKey;
const cache = options.cache ?? (0, response_cache_1.createInMemoryCache)();
const enabled = options.enabled ?? (() => true);
return {
onPluginInit({ addPlugin }) {
addPlugin((0, response_cache_1.useResponseCache)({
...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);
}
},
};
}
exports.useResponseCache = useResponseCache;
;