Uecko_ERP/apps/server/src/lib/modules/service-registry.ts

70 lines
1.7 KiB
TypeScript
Raw Normal View History

2025-09-12 16:23:36 +00:00
const services: Record<string, unknown> = {};
2025-05-04 20:06:57 +00:00
/**
* Registra un objeto de servicio (API) bajo un nombre.
*/
2026-05-05 11:34:36 +00:00
export function registerService(name: string, api: unknown) {
2026-06-13 12:58:09 +00:00
console.debug(`Registering service: ${name}`);
2025-05-04 20:06:57 +00:00
if (services[name]) {
throw new Error(`❌ Servicio "${name}" ya fue registrado.`);
}
services[name] = api;
}
/**
* Recupera un servicio registrado bajo un "scope".
2026-03-28 21:10:05 +00:00
*
* getService("customers:repository")
* Debe declarar: dependencies: ["customers"]
2026-03-28 21:10:05 +00:00
*
* El "scope" puede ser "self" para recuperar
* los servicios propios registrados.
*
* getService("self:repository")
*/
2026-05-05 11:34:36 +00:00
export function getServiceScoped<T = unknown>(
requesterModule: string,
allowedDeps: readonly string[],
name: string
): T {
2026-03-28 21:10:05 +00:00
const [serviceModule, ...key] = name.split(":");
if (serviceModule === "self") {
return getService<T>(`${requesterModule}:${key.join(":")}`);
}
if (!allowedDeps.includes(serviceModule)) {
throw new Error(
`❌ Module "${requesterModule}" tried to access service "${name}" ` +
`without declaring dependency on "${serviceModule}"`
);
}
return getService<T>(name);
}
2025-05-04 20:06:57 +00:00
/**
* Recupera un servicio registrado, con tipado opcional.
*/
2026-05-05 11:34:36 +00:00
function getService<T = unknown>(name: string): T {
2025-05-04 20:06:57 +00:00
const service = services[name];
if (!service) {
throw new Error(`❌ Servicio "${name}" no encontrado.`);
}
2025-10-28 17:52:30 +00:00
return service as T;
2025-05-04 20:06:57 +00:00
}
/**
* Permite saber si un servicio fue registrado.
*/
export function hasService(name: string): boolean {
return !!services[name];
}
/**
* Devuelve todos los servicios (para depuración o tests).
*/
export function listServices(): string[] {
return Object.keys(services);
}