UNPKG

@vtex/api

Version:
44 lines (43 loc) 2.38 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.memoizationMiddleware = void 0; const cache_1 = require("./cache"); const memoizationMiddleware = ({ memoizedCache }) => { return async (ctx, next) => { var _a; if (!(0, cache_1.isLocallyCacheable)(ctx.config, cache_1.CacheType.Any) || !ctx.config.memoizable) { return next(); } const span = (_a = ctx.tracing) === null || _a === void 0 ? void 0 : _a.rootSpan; const key = (0, cache_1.cacheKey)(ctx.config); const isMemoized = !!memoizedCache.has(key); span === null || span === void 0 ? void 0 : span.log({ event: "cache-key-created" /* HttpLogEvents.CACHE_KEY_CREATE */, ["cache-type" /* HttpCacheLogFields.CACHE_TYPE */]: 'memoization', ["key" /* HttpCacheLogFields.KEY */]: key }); if (isMemoized) { span === null || span === void 0 ? void 0 : span.setTag("http.cache.memoization" /* CustomHttpTags.HTTP_MEMOIZATION_CACHE_RESULT */, "HIT" /* CacheResult.HIT */); const memoized = await memoizedCache.get(key); ctx.memoizedHit = isMemoized; ctx.response = memoized.response; return; } else { span === null || span === void 0 ? void 0 : span.setTag("http.cache.memoization" /* CustomHttpTags.HTTP_MEMOIZATION_CACHE_RESULT */, "MISS" /* CacheResult.MISS */); const promise = new Promise(async (resolve, reject) => { try { await next(); resolve({ cacheHit: ctx.cacheHit, response: ctx.response, }); span === null || span === void 0 ? void 0 : span.log({ event: "memoization-cache-saved" /* HttpLogEvents.MEMOIZATION_CACHE_SAVED */, ["key-set" /* HttpCacheLogFields.KEY_SET */]: key }); } catch (err) { reject(err); span === null || span === void 0 ? void 0 : span.log({ event: "memoization-cache-saved-error" /* HttpLogEvents.MEMOIZATION_CACHE_SAVED_ERROR */, ["key-set" /* HttpCacheLogFields.KEY_SET */]: key }); } }); memoizedCache.set(key, promise); await promise; } }; }; exports.memoizationMiddleware = memoizationMiddleware;