From 47b0ec8f9a7f1bb99ee728d08f6982c6e832f2e0 Mon Sep 17 00:00:00 2001 From: ImBenji Date: Wed, 31 Dec 2025 07:32:09 +0000 Subject: [PATCH] Implement cache cleanup for images older than 24 hours and update access time on read --- api.js | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/api.js b/api.js index 625dde0..995fa84 100644 --- a/api.js +++ b/api.js @@ -29,6 +29,9 @@ function getCachedImage(config) { const cachePath = getCachePath(hash); if (fs.existsSync(cachePath)) { + // Update file modification time to mark as recently accessed + const now = new Date(); + fs.utimesSync(cachePath, now, now); return fs.readFileSync(cachePath); } @@ -41,6 +44,33 @@ function cacheImage(config, imageBuffer) { fs.writeFileSync(cachePath, imageBuffer); } +function cleanupOldCache() { + const ONE_DAY = 24 * 60 * 60 * 1000; // 24 hours in milliseconds + const now = Date.now(); + + if (!fs.existsSync(CACHE_DIR)) { + return; + } + + const files = fs.readdirSync(CACHE_DIR); + + let deletedCount = 0; + files.forEach(file => { + const filePath = path.join(CACHE_DIR, file); + const stats = fs.statSync(filePath); + + // Check if file was last modified more than 24 hours ago + if (now - stats.mtime.getTime() > ONE_DAY) { + fs.unlinkSync(filePath); + deletedCount++; + } + }); + + if (deletedCount > 0) { + console.log(`Cleaned up ${deletedCount} cached image(s)`); + } +} + function formatTimestamp(epoch) { const date = new Date(epoch * 1000); @@ -160,8 +190,17 @@ app.get('/health', (req, res) => { res.status(200).json({ status: 'ok' }); }); +// 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×tamp=1735574400`); console.log(`POST: http://localhost:${PORT}/generate`); + console.log(`Cache cleanup runs every hour, images older than 24h are removed`); });