File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 11import abc
2+ from typing import Set
23from allocation .domain import model
34
45
@@ -15,9 +16,14 @@ def get(self, sku) -> model.Product:
1516class SqlAlchemyRepository (AbstractRepository ):
1617 def __init__ (self , session ):
1718 self .session = session
19+ self .seen = set () # type: Set[model.Product]
1820
1921 def add (self , product ):
22+ self .seen .add (product )
2023 self .session .add (product )
2124
2225 def get (self , sku ):
23- return self .session .query (model .Product ).filter_by (sku = sku ).first ()
26+ product = self .session .query (model .Product ).filter_by (sku = sku ).first ()
27+ if product :
28+ self .seen .add (product )
29+ return product
Original file line number Diff line number Diff line change 44
55from allocation .domain import model
66from allocation .domain .model import OrderLine
7- from . import messagebus
87
98if TYPE_CHECKING :
109 from . import unit_of_work
@@ -36,9 +35,6 @@ def allocate(
3635 product = uow .products .get (sku = line .sku )
3736 if product is None :
3837 raise InvalidSku (f"Invalid sku { line .sku } " )
39- try :
40- batchref = product .allocate (line )
41- uow .commit ()
42- return batchref
43- finally :
44- messagebus .handle (product .events )
38+ batchref = product .allocate (line )
39+ uow .commit ()
40+ return batchref
Original file line number Diff line number Diff line change 55from sqlalchemy .orm import sessionmaker
66from sqlalchemy .orm .session import Session
77
8+
89from allocation import config
910from allocation .adapters import repository
11+ from . import messagebus
1012
1113
1214class AbstractUnitOfWork (abc .ABC ):
@@ -18,8 +20,18 @@ def __enter__(self) -> AbstractUnitOfWork:
1820 def __exit__ (self , * args ):
1921 self .rollback ()
2022
21- @abc .abstractmethod
2223 def commit (self ):
24+ self ._commit ()
25+ self .publish_events ()
26+
27+ def publish_events (self ):
28+ for product in self .products .seen :
29+ while product .events :
30+ event = product .events .pop (0 )
31+ messagebus .handle (event )
32+
33+ @abc .abstractmethod
34+ def _commit (self ):
2335 raise NotImplementedError
2436
2537 @abc .abstractmethod
@@ -48,7 +60,7 @@ def __exit__(self, *args):
4860 super ().__exit__ (* args )
4961 self .session .close ()
5062
51- def commit (self ):
63+ def _commit (self ):
5264 self .session .commit ()
5365
5466 def rollback (self ):
Original file line number Diff line number Diff line change @@ -20,7 +20,7 @@ def __init__(self):
2020 self .products = FakeRepository ([])
2121 self .committed = False
2222
23- def commit (self ):
23+ def _commit (self ):
2424 self .committed = True
2525
2626 def rollback (self ):
You can’t perform that action at this time.
0 commit comments