UNPKG

@figmarine/cache

Version:

Library to cache arbitrary data to disk for arbitrarily long

39 lines (36 loc) 1.38 kB
// src/index.ts import fs from "node:fs"; import path2 from "node:path"; import { Cacheable } from "cacheable"; import { Keyv } from "keyv"; import { KeyvFile } from "keyv-file"; import KeyvGzip from "@keyv/compress-gzip"; import { log } from "@figmarine/logger"; // src/constants.ts import os from "node:os"; import path from "node:path"; var DEFAULT_CACHE_PATH = path.join(os.tmpdir(), "@figmarine/cache"); var YEAR_IN_SECONDS = 31556926; // src/index.ts function makeCache(opts) { const { ttl = -1, location } = opts; const finalCacheDirname = path2.isAbsolute(location) ? location : path2.join(DEFAULT_CACHE_PATH, location); const finalCacheFilename = path2.join(finalCacheDirname, "cache.json.gz"); log(`Initialising / reloading cache from location ${finalCacheFilename}`); fs.mkdirSync(finalCacheDirname, { recursive: true }); const computedTtl = 1e3 * (ttl === -1 ? YEAR_IN_SECONDS : ttl); const store = new KeyvFile({ filename: finalCacheFilename, expiredCheckDelay: computedTtl, writeDelay: 100 }); const shutdownGracefully = async () => { }; const primary = new Keyv({ compression: new KeyvGzip(), store, ttl: computedTtl }); const cache = new Cacheable({ primary }); log(`Created cache with ${ttl === -1 ? "infinite TTL (dev mode)" : `${ttl} second TTL`}`); return { cache, primary, shutdownGracefully }; } export { makeCache };