games_app/backend/dist/utils/analyticsCache.js
2026-06-29 15:01:23 +02:00

58 lines
2.1 KiB
JavaScript

"use strict";
/** In-memory TTL cache for admin dashboard analytics responses. */
Object.defineProperty(exports, "__esModule", { value: true });
exports.getCachedDashboardAnalytics = getCachedDashboardAnalytics;
exports.setCachedDashboardAnalytics = setCachedDashboardAnalytics;
exports.invalidateDashboardAnalyticsCache = invalidateDashboardAnalyticsCache;
exports.getCachedSecurityKpis = getCachedSecurityKpis;
exports.setCachedSecurityKpis = setCachedSecurityKpis;
exports.invalidateSecurityKpisCache = invalidateSecurityKpisCache;
const DEFAULT_TTL_MS = Math.max(5000, parseInt(process.env.ANALYTICS_CACHE_TTL_MS ?? '60000', 10));
const cache = new Map();
function cacheKey(query) {
return JSON.stringify({
preset: query.preset ?? 'today',
from: query.from ?? '',
to: query.to ?? '',
gameKey: query.gameKey ?? 'all',
});
}
function getCachedDashboardAnalytics(query) {
const key = cacheKey(query);
const hit = cache.get(key);
if (!hit)
return null;
if (Date.now() > hit.expiresAt) {
cache.delete(key);
return null;
}
return hit.data;
}
function setCachedDashboardAnalytics(query, data, ttlMs = DEFAULT_TTL_MS) {
const key = cacheKey(query);
cache.set(key, { expiresAt: Date.now() + ttlMs, data });
if (cache.size > 48) {
const oldest = [...cache.entries()].sort((a, b) => a[1].expiresAt - b[1].expiresAt)[0];
if (oldest)
cache.delete(oldest[0]);
}
}
function invalidateDashboardAnalyticsCache() {
cache.clear();
}
const SECURITY_TTL_MS = Math.max(60000, parseInt(process.env.ANALYTICS_SECURITY_CACHE_TTL_MS ?? '300000', 10));
let securityCache = null;
function getCachedSecurityKpis() {
if (!securityCache || Date.now() > securityCache.expiresAt) {
securityCache = null;
return null;
}
return securityCache.data;
}
function setCachedSecurityKpis(data) {
securityCache = { expiresAt: Date.now() + SECURITY_TTL_MS, data };
}
function invalidateSecurityKpisCache() {
securityCache = null;
}
//# sourceMappingURL=analyticsCache.js.map