UNPKG

@praha/envelop-request-cache

Version:

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

31 lines (30 loc) 1.46 kB
import { AsyncLocalStorage } from "node:async_hooks"; const createRequestCachePlugin = (options = {})=>{ const storage = options.storage ?? new 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(); export { cache, createRequestCachePlugin, evict, useRequestCache };