@siva-sub/mcp-public-transport
Version:
A Model Context Protocol server for Singapore transport data with real-time information and routing
77 lines (76 loc) • 2.4 kB
JavaScript
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.CacheService = void 0;
const node_cache_1 = __importDefault(require("node-cache"));
const logger_js_1 = require("../utils/logger.js");
class CacheService {
constructor(defaultTtl = 300) {
this.hitCount = 0;
this.missCount = 0;
this.cache = new node_cache_1.default({
stdTTL: defaultTtl,
checkperiod: 60,
useClones: false,
deleteOnExpire: true,
});
this.cache.on('expired', (key) => {
logger_js_1.logger.debug(`Cache key expired: ${key}`);
});
this.cache.on('del', (key) => {
logger_js_1.logger.debug(`Cache key deleted: ${key}`);
});
}
async getOrSet(key, fetchFn, ttl) {
const cached = this.cache.get(key);
if (cached !== undefined) {
this.hitCount++;
logger_js_1.logger.debug(`Cache hit: ${key}`);
return cached;
}
this.missCount++;
logger_js_1.logger.debug(`Cache miss: ${key}`);
try {
const data = await fetchFn();
this.cache.set(key, data, ttl || 300);
logger_js_1.logger.debug(`Cache set: ${key} (TTL: ${ttl || 'default'})`);
return data;
}
catch (error) {
logger_js_1.logger.error(`Failed to fetch data for cache key: ${key}`, error);
throw error;
}
}
get(key) {
const value = this.cache.get(key);
if (value !== undefined) {
this.hitCount++;
}
else {
this.missCount++;
}
return value;
}
set(key, value, ttl) {
return this.cache.set(key, value, ttl || 300);
}
del(key) {
return this.cache.del(key);
}
flush() {
this.cache.flushAll();
logger_js_1.logger.info('Cache flushed');
}
getStats() {
const cacheStats = this.cache.getStats();
return {
...cacheStats,
hitRate: this.hitCount / (this.hitCount + this.missCount) || 0,
hitCount: this.hitCount,
missCount: this.missCount,
};
}
}
exports.CacheService = CacheService;