Refactors loading function
* Initialize service component and handler in hooks * Dynamically watch the config instead of a reload on each page * Uses derived store for public server config * Moves service data in its own page data property * Reverts to a array to store group/services
This commit is contained in:
@@ -1,33 +1,43 @@
|
||||
import type { ServiceHandler } from './service';
|
||||
|
||||
const services: Record<string, [ServiceHandler, string]> = {};
|
||||
type ServiceRecord = {
|
||||
handler: ServiceHandler;
|
||||
component: any;
|
||||
};
|
||||
|
||||
function registerService(type: string, handler: ServiceHandler) {
|
||||
services[type] = [handler, type];
|
||||
const services: Record<string, ServiceRecord> = {};
|
||||
|
||||
function registerService(type: string, handler: ServiceHandler, component: any) {
|
||||
services[type] = { handler, component };
|
||||
}
|
||||
|
||||
export function getService(type: string): [ServiceHandler, string] {
|
||||
const handler = services[type];
|
||||
if (handler == undefined) {
|
||||
return [
|
||||
() => {
|
||||
return { data: {}, componentPath: '' };
|
||||
},
|
||||
''
|
||||
];
|
||||
}
|
||||
return handler;
|
||||
export function getServiceHandler(type: string): ServiceHandler | undefined {
|
||||
return services[type]?.handler;
|
||||
}
|
||||
|
||||
export function getServiceComponent(type: string): any {
|
||||
return services[type]?.component;
|
||||
}
|
||||
|
||||
export async function initServices() {
|
||||
const services = import.meta.glob('/src/lib/services/**/+service.ts');
|
||||
|
||||
for (const [path, load] of Object.entries(services)) {
|
||||
const { handle } = (await load()) as any;
|
||||
if (handle == undefined) {
|
||||
continue;
|
||||
for (const [modulePath, load] of Object.entries(services)) {
|
||||
try {
|
||||
const { handle, path } = (await load()) as any;
|
||||
if (handle == undefined) {
|
||||
throw new Error(`${modulePath} does not export 'handle'`);
|
||||
}
|
||||
if (path == undefined) {
|
||||
throw new Error(`${modulePath} does not export 'path'`);
|
||||
}
|
||||
|
||||
const module = await import(/* @vite-ignore */ '/src/lib/services/' + path);
|
||||
|
||||
const typeName = modulePath.slice(18, -12);
|
||||
registerService(typeName, handle, module.default);
|
||||
} catch (err) {
|
||||
console.error(`Could not load service definition from '${modulePath}': ${err}`);
|
||||
}
|
||||
const typeName = path.slice(18, -12);
|
||||
registerService(typeName, handle);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user