UNPKG

@praha/envelop-request-cache

Version:

This plugin caches arbitrary values within the request scope to optimize execution flow

74 lines (73 loc) 3.01 kB
"use strict"; var __webpack_require__ = {}; (()=>{ __webpack_require__.d = (exports1, definition)=>{ for(var key in definition)if (__webpack_require__.o(definition, key) && !__webpack_require__.o(exports1, key)) Object.defineProperty(exports1, key, { enumerable: true, get: definition[key] }); }; })(); (()=>{ __webpack_require__.o = (obj, prop)=>Object.prototype.hasOwnProperty.call(obj, prop); })(); (()=>{ __webpack_require__.r = (exports1)=>{ if ('undefined' != typeof Symbol && Symbol.toStringTag) Object.defineProperty(exports1, Symbol.toStringTag, { value: 'Module' }); Object.defineProperty(exports1, '__esModule', { value: true }); }; })(); var __webpack_exports__ = {}; __webpack_require__.r(__webpack_exports__); __webpack_require__.d(__webpack_exports__, { cache: ()=>cache, createRequestCachePlugin: ()=>createRequestCachePlugin, evict: ()=>evict, useRequestCache: ()=>useRequestCache }); const external_node_async_hooks_namespaceObject = require("node:async_hooks"); const createRequestCachePlugin = (options = {})=>{ const storage = options.storage ?? new external_node_async_hooks_namespaceObject.AsyncLocalStorage(); return { cache: (callback, keys)=>(...args)=>{ const store = storage.getStore(); if (!store) throw new Error('Request cache is not available. Make sure to use the "useRequestCache" plugin during execution.'); const key = `${callback.toString()}-${JSON.stringify(args)}${keys ? `-[${keys.join(',')}]` : ''}`; const cached = store[key]; if (cached) return cached; const result = callback(...args); store[key] = result; return result; }, evict: ()=>{ const store = storage.getStore(); if (!store) throw new Error('Request cache is not available. Make sure to use the "useRequestCache" plugin during execution.'); Object.keys(store).forEach((key)=>{ delete store[key]; }); }, useRequestCache: ()=>({ onExecute: ({ executeFn, setExecuteFn })=>{ setExecuteFn(async (arguments_)=>storage.run({}, async ()=>await executeFn(arguments_))); } }) }; }; const { cache, evict, useRequestCache } = createRequestCachePlugin(); exports.cache = __webpack_exports__.cache; exports.createRequestCachePlugin = __webpack_exports__.createRequestCachePlugin; exports.evict = __webpack_exports__.evict; exports.useRequestCache = __webpack_exports__.useRequestCache; for(var __webpack_i__ in __webpack_exports__)if (-1 === [ "cache", "createRequestCachePlugin", "evict", "useRequestCache" ].indexOf(__webpack_i__)) exports[__webpack_i__] = __webpack_exports__[__webpack_i__]; Object.defineProperty(exports, '__esModule', { value: true });