Add cache clearing function and invoke on startup
This commit is contained in:
22
api.js
22
api.js
@@ -44,6 +44,20 @@ function cacheImage(config, imageBuffer) {
|
|||||||
fs.writeFileSync(cachePath, 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() {
|
function cleanupOldCache() {
|
||||||
const ONE_DAY = 24 * 60 * 60 * 1000; // 24 hours in milliseconds
|
const ONE_DAY = 24 * 60 * 60 * 1000; // 24 hours in milliseconds
|
||||||
const now = Date.now();
|
const now = Date.now();
|
||||||
@@ -190,17 +204,17 @@ app.get('/health', (req, res) => {
|
|||||||
res.status(200).json({ status: 'ok' });
|
res.status(200).json({ status: 'ok' });
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Clear all cache on startup
|
||||||
|
clearCache();
|
||||||
|
|
||||||
// Run cleanup every hour
|
// Run cleanup every hour
|
||||||
setInterval(() => {
|
setInterval(() => {
|
||||||
cleanupOldCache();
|
cleanupOldCache();
|
||||||
}, 60 * 60 * 1000);
|
}, 60 * 60 * 1000);
|
||||||
|
|
||||||
// Run cleanup on startup
|
|
||||||
cleanupOldCache();
|
|
||||||
|
|
||||||
app.listen(PORT, () => {
|
app.listen(PORT, () => {
|
||||||
console.log(`Quote generator API running on http://localhost:${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(`GET: http://localhost:${PORT}/generate?text=Hello&displayName=Test&username=@test×tamp=1735574400`);
|
||||||
console.log(`POST: http://localhost:${PORT}/generate`);
|
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`);
|
||||||
});
|
});
|
||||||
|
|||||||
Reference in New Issue
Block a user