2025-07-26 13:44:32 +01:00
|
|
|
import { existsSync } from "node:fs";
|
|
|
|
import { readFile, writeFile } from "node:fs/promises";
|
|
|
|
import { resolve } from "node:path";
|
|
|
|
|
|
|
|
/**
|
|
|
|
*
|
|
|
|
* @template T
|
|
|
|
* @param {string} fileName
|
|
|
|
* @param {()=>Promise<T>} asyncCallback
|
|
|
|
* @returns {Promise<T>}
|
|
|
|
*/
|
2025-08-15 04:01:08 +01:00
|
|
|
export async function cacheFunctionOutput(fileName, asyncCallback, silent=false) {
|
2025-08-07 19:32:41 +01:00
|
|
|
const fileLoc = resolve('../cache-repos', fileName);
|
2025-07-26 13:44:32 +01:00
|
|
|
if (existsSync(fileLoc)) {
|
2025-08-15 04:01:08 +01:00
|
|
|
!silent && console.log("[cacher] Using cached ", fileLoc);
|
2025-07-26 13:44:32 +01:00
|
|
|
const fileContents = (await readFile(fileLoc)).toString();
|
|
|
|
return JSON.parse(fileContents);
|
|
|
|
} else {
|
2025-08-15 04:01:08 +01:00
|
|
|
!silent && console.log("[cacher] cache miss")
|
2025-07-26 13:44:32 +01:00
|
|
|
const returnRes = await asyncCallback();
|
|
|
|
const fileContents = JSON.stringify(returnRes);
|
|
|
|
await writeFile(fileLoc,fileContents);
|
2025-08-15 04:01:08 +01:00
|
|
|
!silent && console.log("[cacher] saved ",fileLoc)
|
2025-07-26 13:44:32 +01:00
|
|
|
return returnRes;
|
|
|
|
}
|
|
|
|
}
|