curli-bus
Version:
Simple Command Bus Implementation (CQRS) for NodeJS/Typescript.
35 lines (34 loc) • 1.27 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
const HandlerModel_1 = require("./HandlerModel");
class HandlersCollection {
constructor() {
this.collection = [];
}
add(commandName, handler) {
this.checkIfAlreadyExistCommandWithSameName(commandName);
this.collection.push(new HandlerModel_1.HandlerModel(commandName, handler));
}
dispatch(commandName, command, options) {
let result;
const handlerModel = this.findHandlerByCommand(commandName);
if (handlerModel) {
result = handlerModel.callHandler(command, options);
}
else {
throw new Error('Unable to find a handler for the command ' + commandName + '.');
}
return result;
}
checkIfAlreadyExistCommandWithSameName(commandName) {
if (this.findHandlerByCommand(commandName)) {
throw new Error('This command (' + commandName + ') is already registered.');
}
}
findHandlerByCommand(commandName) {
return this.collection.find((handlerModel) => {
return handlerModel.isThisCommandName(commandName);
});
}
}
exports.HandlersCollection = HandlersCollection;