|
1 | 1 | from __future__ import annotations |
2 | | -from typing import List, Dict, Callable, Type, TYPE_CHECKING |
3 | | -from allocation import events, handlers |
| 2 | +import traceback |
| 3 | +from typing import List, Dict, Callable, Type, Union, TYPE_CHECKING |
| 4 | +from allocation import commands, events, handlers |
| 5 | + |
4 | 6 | if TYPE_CHECKING: |
5 | 7 | from allocation import unit_of_work |
6 | 8 |
|
| 9 | +Message = Union[commands.Command, events.Event] |
7 | 10 |
|
8 | | -def handle(event: events.Event, uow: unit_of_work.AbstractUnitOfWork): |
9 | | - results = [] |
10 | | - for handler in HANDLERS[type(event)]: |
11 | | - r = handler(event, uow=uow) |
12 | | - results.append(r) |
13 | | - return results |
14 | 11 |
|
| 12 | +def handle(message: Message, uow: unit_of_work.AbstractUnitOfWork): |
| 13 | + if isinstance(message, events.Event): |
| 14 | + handle_event(message, uow) |
| 15 | + elif isinstance(message, commands.Command): |
| 16 | + return handle_command(message, uow) |
| 17 | + else: |
| 18 | + raise Exception(f'{message} was not an Event or Command') |
15 | 19 |
|
16 | 20 |
|
17 | | -HANDLERS = { |
18 | | - events.BatchCreated: [handlers.add_batch], |
19 | | - events.BatchQuantityChanged: [handlers.change_batch_quantity], |
20 | | - events.AllocationRequired: [handlers.allocate], |
21 | | - events.OutOfStock: [handlers.send_out_of_stock_notification], |
| 21 | +def handle_event(event: events.Event, uow: unit_of_work.AbstractUnitOfWork): |
| 22 | + for handler in EVENT_HANDLERS[type(event)]: |
| 23 | + try: |
| 24 | + print('handling event', event, 'with handler', handler, flush=True) |
| 25 | + handler(event, uow=uow) |
| 26 | + except: |
| 27 | + print(f'Exception handling event {event}\n:{traceback.format_exc()}') |
| 28 | + continue |
| 29 | + |
| 30 | + |
| 31 | +def handle_command(command, uow: unit_of_work.AbstractUnitOfWork): |
| 32 | + print('handling command', command, flush=True) |
| 33 | + try: |
| 34 | + handler = COMMAND_HANDLERS[type(command)] |
| 35 | + return handler(command, uow=uow) |
| 36 | + except Exception as e: |
| 37 | + print(f'Exception handling command {command}: {e}') |
| 38 | + raise e |
22 | 39 |
|
| 40 | + |
| 41 | +EVENT_HANDLERS = { |
| 42 | + events.OutOfStock: [handlers.send_out_of_stock_notification], |
23 | 43 | } # type: Dict[Type[events.Event], List[Callable]] |
| 44 | + |
| 45 | +COMMAND_HANDLERS = { |
| 46 | + commands.Allocate: handlers.allocate, |
| 47 | + commands.CreateBatch: handlers.add_batch, |
| 48 | + commands.ChangeBatchQuantity: handlers.change_batch_quantity, |
| 49 | +} # type: Dict[Type[commands.Command], Callable] |
0 commit comments