import { AppDataSource } from "../database/data-source"; import { OrgRevision } from "../entities/OrgRevision"; interface LogCacheData { currentRevision: OrgRevision | null; updatedAt: Date; } class LogMemoryStore { private cache: LogCacheData = { currentRevision: null, updatedAt: new Date(), }; private readonly REFRESH_INTERVAL = 5 * 60 * 1000; // 5 นาที private isRefreshing = false; private isInitialized = false; private refreshTimer: NodeJS.Timeout | null = null; constructor() { // ไม่ refresh ทันที - รอให้เรียก initialize() หลัง TypeORM ready } // เริ่มต้น cache หลังจาก TypeORM initialize เสร็จ initialize() { if (this.isInitialized) { console.log("[LogMemoryStore] Already initialized"); return; } this.isInitialized = true; this.refreshCache(); this.refreshTimer = setInterval(() => { this.refreshCache(); }, this.REFRESH_INTERVAL); console.log("[LogMemoryStore] Initialized with", this.REFRESH_INTERVAL / 1000, "second refresh interval"); } private async refreshCache() { if (this.isRefreshing) { console.log("[LogMemoryStore] Already refreshing, skipping..."); return; } this.isRefreshing = true; try { const repoRevision = AppDataSource.getRepository(OrgRevision); const revision = await repoRevision.findOne({ where: { orgRevisionIsCurrent: true, orgRevisionIsDraft: false, }, }); this.cache.currentRevision = revision; this.cache.updatedAt = new Date(); console.log( "[LogMemoryStore] Cache refreshed at", this.cache.updatedAt.toISOString(), ); } catch (error) { console.error("[LogMemoryStore] Error refreshing cache:", error); } finally { this.isRefreshing = false; } } getCurrentRevision(): OrgRevision | null { return this.cache.currentRevision; } getLastUpdateTime(): Date { return this.cache.updatedAt; } // สำหรับ shutdown destroy() { if (this.refreshTimer) { clearInterval(this.refreshTimer); this.refreshTimer = null; } } } export const logMemoryStore = new LogMemoryStore();