|
1 | 1 | # pylint: disable=broad-except
|
2 | 2 | from __future__ import annotations
|
3 | 3 | import logging
|
4 |
| -from typing import Union, TYPE_CHECKING |
| 4 | +from typing import Callable, Dict, List, Union, Type, TYPE_CHECKING |
5 | 5 | from allocation.domain import commands, events
|
6 |
| -from . import handlers |
7 | 6 |
|
8 | 7 | if TYPE_CHECKING:
|
9 | 8 | from . import unit_of_work
|
|
13 | 12 | Message = Union[commands.Command, events.Event]
|
14 | 13 |
|
15 | 14 |
|
16 |
| -def handle(message: Message, uow: unit_of_work.AbstractUnitOfWork): |
17 |
| - queue = [message] |
18 |
| - while queue: |
19 |
| - message = queue.pop(0) |
20 |
| - if isinstance(message, events.Event): |
21 |
| - handle_event(message, queue, uow) |
22 |
| - elif isinstance(message, commands.Command): |
23 |
| - handle_command(message, queue, uow) |
24 |
| - else: |
25 |
| - raise Exception(f'{message} was not an Event or Command') |
| 15 | +class MessageBus: |
| 16 | + |
| 17 | + def __init__( |
| 18 | + self, |
| 19 | + uow: unit_of_work.AbstractUnitOfWork, |
| 20 | + event_handlers: Dict[Type[events.Event], List[Callable]], |
| 21 | + command_handlers: Dict[Type[commands.Command], Callable], |
| 22 | + ): |
| 23 | + self.uow = uow |
| 24 | + self.event_handlers = event_handlers |
| 25 | + self.command_handlers = command_handlers |
| 26 | + |
| 27 | + def handle(self, message: Message): |
| 28 | + self.queue = [message] |
| 29 | + while self.queue: |
| 30 | + message = self.queue.pop(0) |
| 31 | + if isinstance(message, events.Event): |
| 32 | + self.handle_event(message) |
| 33 | + elif isinstance(message, commands.Command): |
| 34 | + self.handle_command(message) |
| 35 | + else: |
| 36 | + raise Exception(f'{message} was not an Event or Command') |
26 | 37 |
|
27 | 38 |
|
28 | 39 | def handle_event(
|
|
0 commit comments