import { eq } from 'drizzle-orm' import type { PostgresJsDatabase } from 'drizzle-orm/postgres-js' import { appConfig } from '../db/schema/stores.js' let configCache: Map | null = null export const AppConfigService = { async getAll(db: PostgresJsDatabase) { return db.select().from(appConfig) }, async get(db: PostgresJsDatabase, key: string): Promise { if (!configCache) await this.refreshCache(db) return configCache!.get(key) ?? null }, async set(db: PostgresJsDatabase, key: string, value: string | null, description?: string) { const [existing] = await db.select().from(appConfig).where(eq(appConfig.key, key)).limit(1) if (existing) { const [updated] = await db .update(appConfig) .set({ value, updatedAt: new Date(), ...(description !== undefined ? { description } : {}) }) .where(eq(appConfig.key, key)) .returning() configCache = null return updated } const [inserted] = await db .insert(appConfig) .values({ key, value, description, updatedAt: new Date() }) .returning() configCache = null return inserted }, async refreshCache(db: PostgresJsDatabase) { const rows = await db.select({ key: appConfig.key, value: appConfig.value }).from(appConfig) configCache = new Map(rows.map((r) => [r.key, r.value])) }, invalidateCache() { configCache = null }, }