Files
flanders/src/lib/services/services.ts

74 lines
2.0 KiB
TypeScript

import type { ServiceConfig } from '$lib/config';
import type { ServiceData, ServicePoller } from './service';
interface ServiceRecord {
poll: ServicePoller;
config: Partial<ServiceConfig>;
}
const services: Record<string, ServiceRecord> = {};
//eslint-disable-next-line @typescript-eslint/no-explicit-any
const components: Record<string, any> = {};
async function pollURL(config: ServiceConfig): Promise<ServiceData> {
const resp = await fetch(config.url);
return { status: resp.ok ? 'online' : 'offline' };
}
function registerService(type: string, service: Partial<ServiceRecord>) {
const record: ServiceRecord = {
poll: service.poll || pollURL,
config: service.config || {}
};
services[type] = record;
}
//eslint-disable-next-line @typescript-eslint/no-explicit-any
function registerComponent(type: string, component: any) {
components[type] = component;
}
export function getServiceRecord(type: string): ServiceRecord {
return services[type] || { poll: pollURL, config: {} };
}
//eslint-disable-next-line @typescript-eslint/no-explicit-any
export function getServiceComponent(type: string): any {
return components[type];
}
export async function initServices() {
const modules = import.meta.glob('/src/lib/services/**/+service.ts');
return Promise.allSettled(
Object.entries(modules).map(async ([path, load]) => {
try {
const { poll, config } = (await load()) as any;
registerService(path.slice(18, -12), { poll, config });
} catch (error) {
console.warn(`could not load ${path}: ${error}`);
}
})
);
}
export async function initComponents() {
const modules = import.meta.glob('/src/lib/services/**/+content.svelte');
return Promise.allSettled(
Object.entries(modules).map(async ([path, load]) => {
try {
const module = (await load()) as any;
if (module == undefined) {
throw new Error('load returned and undefined value');
}
registerComponent(path.slice(18, -16), module.default);
} catch (error) {
console.warn(`could not load ${path}: ${error}`);
}
})
);
}