UNPKG

@remediator/core

Version:
69 lines (68 loc) 2.66 kB
import reMediator from "./reMediator.js"; const defaultOptions = { path: "./app", includeFileNames: [ "*.mediator.command.ts", "*.mediator.query.ts", "*.mediator.middleware.ts", "*.mediator.ts", "*.command.ts", "*.query.ts", "*.middleware.ts", ], }; const colors = { command: "\x1b[36m", query: "\x1b[32m", middleware: "\x1b[33m", reset: "\x1b[0m", }; function globToRegex(glob) { const escaped = glob.replace(/[-[{}()+.,\\^$|#\s]/g, "\\$&"); const regexStr = "^" + escaped.replace(/\*\*/g, ".*").replace(/\*/g, "[^/]*").replace(/\?/g, ".") + "$"; return new RegExp(regexStr); } function logWithColor(type, name) { const color = colors[type]; console.log(`reMediator: [auto] ${color}${type.charAt(0).toUpperCase() + type.slice(1)}${name}${colors.reset}`); } export default function autoRegisterWebpack(options) { const opts = { ...defaultOptions, ...options }; const registered = new Set(); for (const pattern of opts.includeFileNames || []) { const regex = globToRegex(pattern); const ctx = require.context(opts.path || "", true, regex); ctx.keys().forEach((key) => { const mod = ctx(key); Object.entries(mod).forEach(([exportName, exportedValue]) => { if (typeof exportedValue !== "function") return; // Commands & Queries if (exportName.endsWith("Command") || exportName.endsWith("Query")) { if (registered.has(exportName)) return; const handlerExport = `${exportName}Handler`; const HandlerCtor = mod[handlerExport]; if (typeof HandlerCtor === "function") { reMediator.register(exportedValue, new HandlerCtor()); registered.add(exportName); logWithColor(exportName.endsWith("Command") ? "command" : "query", exportName); } else { console.warn(`reMediator: [auto] No handler for ${exportName}. Expect ${handlerExport} in ${key}`); } } // Middleware if (exportName.endsWith("Middleware")) { if (!registered.has(exportName)) { reMediator.use(exportedValue); registered.add(exportName); logWithColor("middleware", exportName); } } }); }); } }