Skip to content

Commit 5afd329

Browse files
committed
bootstrap script preps DI'd handlers and start orm [bootstrap_script]
1 parent 2d0c281 commit 5afd329

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

src/allocation/bootstrap.py

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
import inspect
2+
from typing import Callable
3+
from allocation.adapters import email, orm, redis_eventpublisher
4+
from allocation.service_layer import handlers, messagebus, unit_of_work
5+
6+
7+
def bootstrap(
8+
start_orm: bool = True,
9+
uow: unit_of_work.AbstractUnitOfWork = unit_of_work.SqlAlchemyUnitOfWork(),
10+
send_mail: Callable = email.send,
11+
publish: Callable = redis_eventpublisher.publish,
12+
) -> messagebus.MessageBus:
13+
14+
if start_orm:
15+
orm.start_mappers()
16+
17+
dependencies = {'uow': uow, 'send_mail': send_mail, 'publish': publish}
18+
injected_event_handlers = {
19+
event_type: [
20+
inject_dependencies(handler, dependencies)
21+
for handler in event_handlers
22+
]
23+
for event_type, event_handlers in handlers.EVENT_HANDLERS.items()
24+
}
25+
injected_command_handlers = {
26+
command_type: inject_dependencies(handler, dependencies)
27+
for command_type, handler in handlers.COMMAND_HANDLERS.items()
28+
}
29+
30+
return messagebus.MessageBus(
31+
uow=uow,
32+
event_handlers=injected_event_handlers,
33+
command_handlers=injected_command_handlers,
34+
)
35+
36+
37+
def inject_dependencies(handler, dependencies):
38+
params = inspect.signature(handler).parameters
39+
deps = {
40+
name: dependency
41+
for name, dependency in dependencies.items()
42+
if name in params
43+
}
44+
return lambda message: handler(message, **deps)

0 commit comments

Comments
 (0)