import fsp from 'node:fs/promises'; import path from 'node:path'; import { NodeCache } from '@cacheable/node-cache'; import Debug from 'debug'; import { parseTwtxt } from 'twtxt-lib'; import { TwtKprConfiguration } from '../types.js'; /** * * @param param0 * @returns */ export default function twtxtCache({ publicDirectory, twtxtFilename, }: Pick) { let isLoaded = false; const debug = Debug('twtkpr:twtxtCache'); const cache = new NodeCache(); const reloadCache = async () => { const fileText = await fsp.readFile( path.join(publicDirectory, twtxtFilename), 'utf8' ); const parsedFile = parseTwtxt(fileText); Object.keys(parsedFile).forEach((key) => { cache.set(key, parsedFile[key as keyof typeof parsedFile]); // 10 seconds }); cache.set('source', fileText); debug(`cache ${isLoaded ? 're' : ''}loaded`); isLoaded = true; }; reloadCache(); return { cache, reloadCache, }; }