|
1 | | -import { CommandBus } from './../../domain/CommandBus'; |
2 | 1 | import { Command } from '../../domain/Command'; |
3 | | -import { NoHandlerForMessageError } from './NoHandlerForMessageError'; |
4 | | -import { CommandHandler } from '../../domain/CommandHandler'; |
5 | | - |
6 | | -export class CommandHandlersInformation { |
7 | | - private commandHandlersMap: Map<string, CommandHandler<Command>>; |
8 | | - |
9 | | - constructor(commandHandlers: Array<CommandHandler<Command>>) { |
10 | | - this.commandHandlersMap = this.formatHandlers(commandHandlers); |
11 | | - } |
12 | | - |
13 | | - private formatHandlers(commandHandlers: Array<CommandHandler<Command>>) { |
14 | | - const handlersMap = new Map(); |
15 | | - |
16 | | - commandHandlers.forEach(commandHandler => { |
17 | | - handlersMap.set(commandHandler.subscribedTo(), commandHandler); |
18 | | - }); |
19 | | - |
20 | | - return handlersMap; |
21 | | - } |
22 | | - |
23 | | - public getHandler(command: Command) { |
24 | | - return this.commandHandlersMap.get(command.constructor.name); |
25 | | - } |
26 | | -} |
| 2 | +import { CommandBus } from './../../domain/CommandBus'; |
| 3 | +import { CommandHandlersInformation } from './CommandHandlersInformation'; |
27 | 4 |
|
28 | 5 | export class InMemoryCommandBus implements CommandBus { |
29 | | - constructor(private commandHandlersInformation: CommandHandlersInformation) { |
30 | | - } |
31 | | - |
32 | | - dispatch(command: Command): void { |
33 | | - const handler = this.commandHandlersInformation.getHandler(command); |
| 6 | + constructor(private commandHandlersInformation: CommandHandlersInformation) {} |
34 | 7 |
|
35 | | - if (!handler) { |
36 | | - throw new NoHandlerForMessageError(command); |
37 | | - } |
| 8 | + async dispatch(command: Command): Promise<void> { |
| 9 | + const handler = this.commandHandlersInformation.search(command); |
38 | 10 |
|
39 | | - handler.handle(command); |
| 11 | + await handler.handle(command); |
40 | 12 | } |
41 | 13 | } |
0 commit comments