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