import * as fs from 'fs'; import { Console } from "console"; const CACHE_DIR = process.env["CACHE_DIR"] || ".cache"; const logger = new Console(process.stderr); export type Cache = { (cacheKey: string, cacheGetter: () => Promise): Promise; }; export const withCache : Cache = async function( cacheKey: string, cacheGetter: () => Promise, ): Promise { // Check if cache exists const cachePath = `${CACHE_DIR}/${encodeURIComponent(cacheKey)}`; if (fs.existsSync(cachePath)) { logger.debug("withCache: Using cached value:", cachePath); const val = JSON.parse(fs.readFileSync(cachePath, 'utf8')); return val; } const val = await cacheGetter(); if (val === undefined) throw "withCache: undefined value from cacheGetter"; // Save it if (!fs.existsSync(CACHE_DIR)) { fs.mkdirSync(CACHE_DIR); } logger.debug("withCache: Saving test cache:", cachePath); fs.writeFileSync(cachePath, JSON.stringify(val)); return val; }