refactor: convert DomainService to singleton pattern

Move cache state from module-level variables into instance
properties and use getInstance() to ensure a single shared
instance across routes and CORS configuration.
This commit is contained in:
Darkraise
2026-02-04 11:23:20 +07:00
parent afd835bbd9
commit 855cb8b38c
4 changed files with 25 additions and 16 deletions
+1 -1
View File
@@ -7,7 +7,7 @@ import { logActivity } from '../middleware/activityLogger';
import { logger } from '../utils/logger';
const router = Router();
const domainService = new DomainService();
const domainService = DomainService.getInstance();
// ===================================
// GET ALL DOMAINS
+1 -1
View File
@@ -11,7 +11,7 @@ import { logger } from '../utils/logger';
const router = Router();
const systemSettings = new CachedSystemSettingsService();
const domainService = new DomainService();
const domainService = DomainService.getInstance();
// Helper function to update job scheduler when jobs settings change
function updateJobScheduler(category: string, settings: Record<string, any>): void {
+1 -2
View File
@@ -39,8 +39,7 @@ async function startServer() {
})
);
// Single DomainService instance — reused by CORS and routes
const domainService = new DomainService();
const domainService = DomainService.getInstance();
// CORS - dynamic origin to support configured domains
app.use(
+22 -12
View File
@@ -16,19 +16,29 @@ interface DomainRow {
created_by: number | null;
}
// In-memory cache with TTL
let cachedDomains: Domain[] | null = null;
let cacheTimestamp = 0;
const CACHE_TTL_MS = 60_000; // 60 seconds
export class DomainService {
private static instance: DomainService;
private cachedDomains: Domain[] | null = null;
private cacheTimestamp = 0;
private readonly CACHE_TTL_MS = 60_000; // 60 seconds
private constructor() {}
static getInstance(): DomainService {
if (!DomainService.instance) {
DomainService.instance = new DomainService();
}
return DomainService.instance;
}
private get db() {
return UserDatabaseService.getDatabase();
}
private invalidateCache(): void {
cachedDomains = null;
cacheTimestamp = 0;
this.cachedDomains = null;
this.cacheTimestamp = 0;
}
private mapRow(row: DomainRow): Domain {
@@ -45,8 +55,8 @@ export class DomainService {
*/
getAllDomains(): Domain[] {
const now = Date.now();
if (cachedDomains && now - cacheTimestamp < CACHE_TTL_MS) {
return cachedDomains;
if (this.cachedDomains && now - this.cacheTimestamp < this.CACHE_TTL_MS) {
return this.cachedDomains;
}
const rows = this.db
@@ -55,9 +65,9 @@ export class DomainService {
)
.all() as DomainRow[];
cachedDomains = rows.map(this.mapRow);
cacheTimestamp = now;
return cachedDomains;
this.cachedDomains = rows.map(this.mapRow);
this.cacheTimestamp = now;
return this.cachedDomains;
}
/**