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.
56 lines
2.3 KiB
56 lines
2.3 KiB
|
|
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");
|
|
}
|
|
|
|
declare module "h3" {
|
|
interface H3EventContext {
|
|
auth: ReturnType<typeof createAuthContext>;
|
|
config: {
|
|
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>>;
|
|
};
|
|
}
|
|
}
|
|
|
|
export default defineNitroPlugin((nitroApp) => {
|
|
nitroApp.hooks.hook("request", (event) => {
|
|
const requestCache = new Map<string, Promise<unknown>>();
|
|
event.context.auth = createAuthContext(event);
|
|
|
|
event.context.config = {
|
|
getGlobal: async <K extends KnownConfigKey>(key: K) => {
|
|
const cacheKey = `global:${key}`;
|
|
if (!requestCache.has(cacheKey)) {
|
|
requestCache.set(cacheKey, getGlobalConfigValue(key));
|
|
}
|
|
return requestCache.get(cacheKey) as Promise<KnownConfigValue<K>>;
|
|
},
|
|
getUser: async <K extends KnownConfigKey>(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<KnownConfigValue<K> | undefined>;
|
|
},
|
|
get: async <K extends KnownConfigKey>(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<KnownConfigValue<K>>;
|
|
},
|
|
};
|
|
});
|
|
})
|
|
|