UNPKG

alpha-command-bus

Version:
64 lines (63 loc) 2.1 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.CommandBus = void 0; const CommandHandlerDescriptor_1 = require("./CommandHandlerDescriptor"); class CommandBus { constructor() { this.middlewares = []; this.commandHandlers = []; } /** * Registers middleware that wraps process of handling a command */ use(middleware) { this.middlewares.push(middleware); return this; } registerCommandHandler(filterOrDescriptor, handler) { if (filterOrDescriptor instanceof CommandHandlerDescriptor_1.CommandHandlerDescriptor) { this.commandHandlers.push(filterOrDescriptor); } else { this.commandHandlers.push(CommandHandlerDescriptor_1.CommandHandlerDescriptor.fromFilter(filterOrDescriptor, handler)); } return this; } registerCommandHandlers(descriptors) { for (const descriptor of descriptors) { this.registerCommandHandler(descriptor); } return this; } /** * Dispatches command to the bus. */ async handle(command) { let currentMiddleware = 0; const next = (command) => { const middleware = this.middlewares[currentMiddleware++]; if (middleware) { return middleware(command, next); } return this.runCommandHandler(command); }; return next(command); } asCommandRunner() { return this.handle.bind(this); } hasCommandHandler(command) { return !!this.getCommandHandlerForCommand(command); } runCommandHandler(command) { const commandHandler = this.getCommandHandlerForCommand(command); if (!commandHandler) { throw new Error(`No command handler registered for command: ${command.command}`); } return commandHandler.func(command); } getCommandHandlerForCommand(command) { return this.commandHandlers.find(({ predicate }) => predicate(command)); } } exports.CommandBus = CommandBus;