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"); } export default defineNitroPlugin((nitroApp) => { nitroApp.hooks.hook("request", (event) => { const requestCache = new Map>(); event.context.auth = createAuthContext(event); event.context.config = { getGlobal: async (key: K) => { const cacheKey = `global:${key}`; if (!requestCache.has(cacheKey)) { requestCache.set(cacheKey, getGlobalConfigValue(key)); } return requestCache.get(cacheKey) as Promise>; }, getUser: async (key: K) => { const cacheKey = `user:${key}`; if (!requestCache.has(cacheKey)) { requestCache.set(cacheKey, (async () => { const user = await event.context.auth.getCurrent(); return getUserConfigValue(user?.id, key); })()); } return requestCache.get(cacheKey) as Promise | undefined>; }, get: async (key: K) => { const cacheKey = `merged:${key}`; if (!requestCache.has(cacheKey)) { requestCache.set(cacheKey, (async () => { const user = await event.context.auth.getCurrent(); return getMergedConfigValue(user?.id, key); })()); } return requestCache.get(cacheKey) as Promise>; }, }; }); })