You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
68 lines
2.7 KiB
68 lines
2.7 KiB
|
|
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: <K extends KnownConfigKey>(key: K) => Promise<KnownConfigValue<K>>;
|
|
getUser: <K extends KnownConfigKey>(key: K) => Promise<KnownConfigValue<K> | undefined>;
|
|
get: <K extends KnownConfigKey>(key: K) => Promise<KnownConfigValue<K>>;
|
|
};
|
|
|
|
interface CachedConfigCache {
|
|
get<T>(key: string): Promise<T | null>;
|
|
set<T>(key: string, value: T, ttl?: number): Promise<void>;
|
|
del(key: string): Promise<void>;
|
|
}
|
|
|
|
declare module "h3" {
|
|
interface H3EventContext {
|
|
auth: ReturnType<typeof createAuthContext>;
|
|
config: ConfigContext;
|
|
cache: ReturnType<typeof createCache>;
|
|
}
|
|
}
|
|
|
|
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 <K extends KnownConfigKey>(key: K) => {
|
|
const cacheKey = `config:global:${key}`;
|
|
const cached = await cache.get<KnownConfigValue<K>>(cacheKey);
|
|
if (cached !== null) return cached;
|
|
const value = await getGlobalConfigValue(key);
|
|
await cache.set(cacheKey, value);
|
|
return value;
|
|
},
|
|
getUser: async <K extends KnownConfigKey>(key: K) => {
|
|
const user = await event.context.auth.getCurrent();
|
|
const cacheKey = `config:user:${user?.id ?? "anonymous"}:${key}`;
|
|
const cached = await cache.get<KnownConfigValue<K>>(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 <K extends KnownConfigKey>(key: K) => {
|
|
const user = await event.context.auth.getCurrent();
|
|
const cacheKey = `config:merged:${user?.id ?? "anonymous"}:${key}`;
|
|
const cached = await cache.get<KnownConfigValue<K>>(cacheKey);
|
|
if (cached !== null) return cached;
|
|
const value = await getMergedConfigValue(user?.id, key);
|
|
await cache.set(cacheKey, value);
|
|
return value;
|
|
},
|
|
};
|
|
});
|
|
})
|
|
|