automatic service registration à la Svelte
This commit is contained in:
33
src/lib/services/services.ts
Normal file
33
src/lib/services/services.ts
Normal file
@@ -0,0 +1,33 @@
|
||||
import type { ServiceHandler } from './service';
|
||||
|
||||
const services: Record<string, [ServiceHandler, string]> = {};
|
||||
|
||||
function registerService(type: string, handler: ServiceHandler) {
|
||||
services[type] = [handler, type];
|
||||
}
|
||||
|
||||
export function getService(type: string): [ServiceHandler, string] {
|
||||
const handler = services[type];
|
||||
if (handler == undefined) {
|
||||
return [
|
||||
() => {
|
||||
return { data: {}, componentPath: '' };
|
||||
},
|
||||
''
|
||||
];
|
||||
}
|
||||
return handler;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
const typeName = path.slice(18, -12);
|
||||
registerService(typeName, handle);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user