import { createCache } from "cache"; import { createAuthContext } from "../service/auth/context"; import { getGlobalConfigValue, getMergedConfigValue, getUserConfigValue } from "../service/config"; import type { KnownConfigKey, KnownConfigValue } from "../service/config/registry"; if (import.meta.dev) { console.log("plugin: 01.context"); } type ConfigContext = { getGlobal: (key: K) => Promise>; getUser: (key: K) => Promise | undefined>; get: (key: K) => Promise>; }; interface CachedConfigCache { get(key: string): Promise; set(key: string, value: T, ttl?: number): Promise; del(key: string): Promise; } declare module "h3" { interface H3EventContext { auth: ReturnType; config: ConfigContext; cache: ReturnType; } } export default defineNitroPlugin((nitroApp) => { nitroApp.hooks.hook("request", async (event) => { event.context.auth = createAuthContext(event); const cache = event.context.cache; event.context.config = { getGlobal: async (key: K) => { const cacheKey = `config:global:${key}`; const cached = await cache.get>(cacheKey); if (cached !== null) return cached; const value = await getGlobalConfigValue(key); await cache.set(cacheKey, value); return value; }, getUser: async (key: K) => { const user = await event.context.auth.getCurrent(); const cacheKey = `config:user:${user?.id ?? "anonymous"}:${key}`; const cached = await cache.get>(cacheKey); if (cached !== null) return cached; const value = await getUserConfigValue(user?.id, key); if (value !== undefined) { await cache.set(cacheKey, value); } return value; }, get: async (key: K) => { const user = await event.context.auth.getCurrent(); const cacheKey = `config:merged:${user?.id ?? "anonymous"}:${key}`; const cached = await cache.get>(cacheKey); if (cached !== null) return cached; const value = await getMergedConfigValue(user?.id, key); await cache.set(cacheKey, value); return value; }, }; }); })