Skip to content

Commit 9c08436

Browse files
committed
messagebus now does events and commands differently [new_messagebus]
1 parent 7292f17 commit 9c08436

1 file changed

Lines changed: 42 additions & 13 deletions

File tree

Lines changed: 42 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,53 @@
1+
# pylint: disable=bare-except
12
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
46
from . import handlers
7+
58
if TYPE_CHECKING:
69
from allocation.service_layer import unit_of_work
710

11+
logger = logging.getLogger(__name__)
812

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]
1514

1615

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
1733

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],
2334

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],
2447
} # 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

Comments
 (0)