import Path from 'path' import File from 'fs/promises' const DIR = '.cache' /** * @param {string} id * @returns {Promise} */ const get = async id => { if (!await File.exists(DIR)) { await File.mkdir(DIR) } const p = Path.join(DIR, id) return (await File.exists(p)) ? (await File.readFile(p)).buffer : undefined } /** * @param {string} id * @param {() => Promise} onMiss * @returns {Promise} */ const tryGet = async (id, onMiss) => { if (!await File.exists(DIR)) { await File.mkdir(DIR) } const p = Path.join(DIR, id) if (!await File.exists(p)) { const buf = await onMiss() await File.writeFile(p, buf) return buf } else { return (await File.readFile(p)).buffer } } /** * @template T * @param {string} id * @param {() => Promise} onMiss * @returns {Promise} */ const tryGetJson = async (id, onMiss) => { const buf = await tryGet(id + '.json', async () => Buffer.from(JSON.stringify(await onMiss()))) return JSON.parse(Buffer.from(buf).toString('utf8')) } export { get, tryGet, tryGetJson }