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
5+
46class AbstractRepository (abc .ABC ):
57
68 @abc .abstractmethod
@@ -17,9 +19,14 @@ class SqlAlchemyRepository(AbstractRepository):
1719
1820 def __init__ (self , session ):
1921 self .session = session
22+ self .seen = set () # type: Set[model.Product]
2023
2124 def add (self , product ):
25+ self .seen .add (product )
2226 self .session .add (product )
2327
2428 def get (self , sku ):
25- return self .session .query (model .Product ).filter_by (sku = sku ).first ()
29+ product = self .session .query (model .Product ).filter_by (sku = sku ).first ()
30+ if product :
31+ self .seen .add (product )
32+ 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
87if TYPE_CHECKING :
98 from . import unit_of_work
109
@@ -35,9 +34,6 @@ def allocate(
3534 product = uow .products .get (sku = line .sku )
3635 if product is None :
3736 raise InvalidSku (f'Invalid sku { line .sku } ' )
38- try :
39- batchref = product .allocate (line )
40- uow .commit ()
41- return batchref
42- finally :
43- messagebus .handle (product .events )
37+ batchref = product .allocate (line )
38+ uow .commit ()
39+ 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
12+
1013
1114
1215class AbstractUnitOfWork (abc .ABC ):
@@ -18,8 +21,18 @@ def __enter__(self) -> AbstractUnitOfWork:
1821 def __exit__ (self , * args ):
1922 self .rollback ()
2023
21- @abc .abstractmethod
2224 def commit (self ):
25+ self ._commit ()
26+ self .publish_events ()
27+
28+ def publish_events (self ):
29+ for product in self .products .seen :
30+ while product .events :
31+ event = product .events .pop (0 )
32+ messagebus .handle (event )
33+
34+ @abc .abstractmethod
35+ def _commit (self ):
2336 raise NotImplementedError
2437
2538 @abc .abstractmethod
@@ -47,7 +60,7 @@ def __exit__(self, *args):
4760 super ().__exit__ (* args )
4861 self .session .close ()
4962
50- def commit (self ):
63+ def _commit (self ):
5164 self .session .commit ()
5265
5366 def rollback (self ):
Original file line number Diff line number Diff line change @@ -22,7 +22,7 @@ def __init__(self):
2222 self .products = FakeRepository ([])
2323 self .committed = False
2424
25- def commit (self ):
25+ def _commit (self ):
2626 self .committed = True
2727
2828 def rollback (self ):
You can’t perform that action at this time.
0 commit comments