UNPKG

@remediator/core

Version:
61 lines (60 loc) 2.53 kB
import reMediator from "./reMediator.js"; const defaultOptions = { path: "/app", includeFileNames: [ "*.mediator.ts", "*.mediator.command.ts", "*.mediator.query.ts", "*.command.ts", "*.query.ts", "*.middleware.ts", ], }; export default function autoRegisterVite(options, globFn) { const opts = { ...defaultOptions, ...options }; // Check if we have a glob function available if (globFn && typeof globFn === "function") { // Use provided glob function const globResults = (opts.includeFileNames || []).map((pattern) => globFn(`${opts.path}/**/${pattern}`, { eager: true })); const modules = Object.assign({}, ...globResults); processModules(modules); } else if (typeof import.meta !== "undefined" && typeof import.meta.glob === "function") { // Use import.meta.glob directly (for static replacement) const globResults = (opts.includeFileNames || []).map((pattern) => import.meta.glob(`${opts.path}/**/${pattern}`, { eager: true })); const modules = Object.assign({}, ...globResults); processModules(modules); } else { console.error("reMediator: No glob function available"); return; } } function processModules(modules) { for (const filePath in modules) { const mod = modules[filePath]; // Iterate through each export in the module Object.entries(mod).forEach(([exportName, exportedValue]) => { if (typeof exportedValue !== "function") return; // Auto-register Commands & Queries by naming convention if (exportName.endsWith("Command") || exportName.endsWith("Query")) { const handlerName = `${exportName}Handler`; const HandlerCtor = mod[handlerName]; if (typeof HandlerCtor === "function") { reMediator.register(exportedValue, new HandlerCtor()); console.log(`reMediator: Registered ${exportName}${handlerName}`); } else { console.warn(`reMediator: No handler found for ${exportName}. Expected export '${handlerName}' in ${filePath}`); } } // Auto-register Middleware if (exportName.endsWith("Middleware")) { reMediator.use(exportedValue); console.log(`reMediator: Registered middleware → ${exportName}`); } }); } }