Add cache clearing function and invoke on startup

This commit is contained in:
ImBenji
2025-12-31 10:36:21 +00:00
parent 084130feb7
commit d4b1dffd74

22
api.js
View File

@@ -44,6 +44,20 @@ function cacheImage(config, imageBuffer) {
fs.writeFileSync(cachePath, imageBuffer);
}
function clearCache() {
if (!fs.existsSync(CACHE_DIR)) {
return;
}
const files = fs.readdirSync(CACHE_DIR);
files.forEach(file => {
const filePath = path.join(CACHE_DIR, file);
fs.unlinkSync(filePath);
});
console.log(`Cleared ${files.length} cached image(s)`);
}
function cleanupOldCache() {
const ONE_DAY = 24 * 60 * 60 * 1000; // 24 hours in milliseconds
const now = Date.now();
@@ -190,17 +204,17 @@ app.get('/health', (req, res) => {
res.status(200).json({ status: 'ok' });
});
// Clear all cache on startup
clearCache();
// Run cleanup every hour
setInterval(() => {
cleanupOldCache();
}, 60 * 60 * 1000);
// Run cleanup on startup
cleanupOldCache();
app.listen(PORT, () => {
console.log(`Quote generator API running on http://localhost:${PORT}`);
console.log(`GET: http://localhost:${PORT}/generate?text=Hello&displayName=Test&username=@test&timestamp=1735574400`);
console.log(`POST: http://localhost:${PORT}/generate`);
console.log(`Cache cleanup runs every hour, images older than 24h are removed`);
console.log(`Cache cleared on startup, cleanup runs every hour`);
});