UNPKG

cqrs-eda

Version:

Lightweight CQRS and Event-Driven Architecture library using TypeScript decorators, handlers and typings. Perfect for scalable event-driven apps.

68 lines (67 loc) 2.48 kB
import glob from "glob"; import path from "path"; import { pathToFileURL } from "url"; /** * Dynamically loads all decorated classes (Commands, Queries, Observers) * so that the internal registries are automatically populated. * * This must be called before using CommandHandler, QueryHandler, or ObserverHandler, * otherwise the handlers won't know about the decorated classes. * * Example without any dependency injection container: * ```ts * import { Utilities, Handlers } from "cqrs-eda"; * * async function bootstrap() { * // Load all decorated commands, queries, and observers * await Utilities.loadDecoratedClasses("src/application"); * * // Initialize handlers * const commandHandler = new Handlers.CommandHandler(); * const queryHandler = new Handlers.QueryHandler(); * const observerHandler = new Handlers.ObserverHandler(); * * // Use the handlers * const segment = await queryHandler.fire("GET_SEGMENT", { phrase: "Hello", accent: "american" }); * console.log(segment); * * await commandHandler.fire("SAVE_SEGMENT", { phrase: "Hello", accent: "american", videoUrl: "...", startTime: 0, endTime: 2 }); * await observerHandler.publish("SEGMENT.SAVED", { phrase: "Hello", accent: "american", ... }); * } * * bootstrap(); * ``` * * @param basePath The base path where decorated files are located (e.g. "src/application") */ export async function loadDecoratedClasses(basePath) { // Ajusta o basePath para dev ou dist const fullPath = path.isAbsolute(basePath) ? basePath : path.join(process.cwd(), basePath); const files = glob.sync(path.join(fullPath, "**/*.js")); // só JS no build if (files.length === 0) { console.warn(`[CQRS-EDA] No decorated classes found in ${fullPath}`); return; } for (const file of files) { try { await import(file.startsWith("file://") ? file : pathToFileURL(file).href); } catch (err) { console.error(`[CQRS-EDA] Error loading file ${file}:`, err); } } } async function test() { const basePath = path.join(process.cwd(), "dist", "application"); // caminho para os arquivos compilados console.log("Carregando classes decoradas de:", basePath); try { await loadDecoratedClasses(basePath); console.log("✅ Classes carregadas com sucesso!"); } catch (err) { console.error("❌ Erro ao carregar classes:", err); } } test();