Files
mpcfill-pdf/cache.js
orion kindel ae5193700a init
2025-11-06 15:16:08 -06:00

52 lines
1.1 KiB
JavaScript

import Path from 'path'
import File from 'fs/promises'
const DIR = '.cache'
/**
* @param {string} id
* @returns {Promise<ArrayBuffer | undefined>}
*/
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<ArrayBuffer>} onMiss
* @returns {Promise<ArrayBuffer>}
*/
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<T>} onMiss
* @returns {Promise<T>}
*/
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 }