cache.handlers.ts•2.42 kB
/**
* Cache route handler functions
*
* These handler functions are extracted from the main routes file
* to enable direct testing without Express router complexities.
*/
import { Request, Response } from 'express';
import { cacheService } from '../utils/cache';
import { logger } from '../utils/logger';
/**
* Handler for GET /cache/stats
* Returns cache statistics
*/
export const statsHandler = (_req: Request, res: Response): void => {
try {
const stats = {
// Get statistics from the cache service
...cacheService.getStats(),
// Calculate time since server start
uptime: process.uptime()
};
res.status(200).json({
success: true,
data: stats
});
} catch (error) {
logger.error('Error getting cache stats:', error);
res.status(500).json({
success: false,
error: error instanceof Error ? error.message : 'Unknown error occurred'
});
}
};
/**
* Handler for DELETE /cache/clear
* Clears all items from cache
*/
export const clearAllHandler = (_req: Request, res: Response): void => {
try {
const count = cacheService.clear();
logger.info(`Cache cleared successfully: ${count} items removed`);
res.status(200).json({
success: true,
message: 'Cache cleared successfully'
});
} catch (error) {
logger.error('Error clearing cache:', error);
res.status(500).json({
success: false,
error: error instanceof Error ? error.message : 'Unknown error occurred'
});
}
};
/**
* Handler for DELETE /cache/clear/:type
* Clears cache for a specific type
*/
export const clearTypeHandler = (req: Request, res: Response): void => {
try {
const { type } = req.params;
// Validate type
if (!['top', 'all', 'similar', 'uuid', 'sources'].includes(type)) {
return res.status(400).json({
success: false,
error: `Invalid cache type: ${type}`
});
}
const keysDeleted = cacheService.deleteByPrefix(`${type}_`);
logger.info(`Cleared ${keysDeleted} cache entries for type: ${type}`);
res.status(200).json({
success: true,
message: `Cleared ${keysDeleted} cache entries for type: ${type}`
});
} catch (error) {
logger.error('Error clearing cache by type:', error);
res.status(500).json({
success: false,
error: error instanceof Error ? error.message : 'Unknown error occurred'
});
}
};