UNPKG

idmp

Version:

A lightweight TypeScript library for deduplicating and caching async function calls with automatic retries, designed for idempotent network requests in React and Node.js.

72 lines (71 loc) 2.22 kB
/*! idmp v4.1.0 | (c) github/haozi | MIT */ import { createHash } from "crypto"; import fs from "fs-extra"; import { getOptions } from "idmp"; import { parse_UNSAFE, stringify_UNSAFE } from "json-web3"; import os from "os"; import path from "path"; import { fileURLToPath } from "url"; //#region src/index.ts var __filename = fileURLToPath(import.meta.url); var md5 = (data) => createHash("md5").update(data).digest("hex"); var deSerialize = (data) => parse_UNSAFE(data); var prefix = md5(__filename); var udf = void 0; var encode = encodeURIComponent; var cacheDir = path.resolve(os.tmpdir(), "idmp"); var getCachePath = (globalKey) => path.resolve(cacheDir, "v4/node", prefix, encode(globalKey)); var setData = async (key, data, maxAge) => { if (!key) return; const cachePath = getCachePath(key); fs.ensureFileSync(cachePath); fs.outputFileSync(cachePath, stringify_UNSAFE({ t: Date.now(), a: maxAge, d: data })); }; var getData = async (key) => { if (!key) return udf; const cachePath = getCachePath(key); let localData; try { localData = deSerialize(fs.readFileSync(cachePath, "utf-8")); } catch {} if (localData === udf) return udf; const { t, a: maxAge, d: data } = localData; if (Date.now() - t > maxAge) { fs.removeSync(cachePath); return udf; } return data; }; var fsIdmpWrap = (_idmp, namespace, extraOptions) => { const newIdmp = (globalKey, promiseFunc, options) => { globalKey = `${namespace}_${globalKey}`; const finalOptions = getOptions(options); const { useMemoryCache } = extraOptions || {}; return _idmp(globalKey, async () => { const localData = await getData(globalKey); if (localData !== udf) return localData; const memoryData = await promiseFunc(); if (memoryData !== udf) setData(globalKey, memoryData, finalOptions.maxAge); return memoryData; }, { ...options, maxAge: useMemoryCache ? finalOptions.maxAge : 200 }); }; newIdmp.flush = (globalKey) => { _idmp.flush(globalKey); fs.removeSync(getCachePath(globalKey)); }; newIdmp.flushAll = () => { _idmp.flushAll(); fs.removeSync(cacheDir); }; return newIdmp; }; //#endregion export { cacheDir, fsIdmpWrap as default, getCachePath }; //# sourceMappingURL=index.js.map