Connecting the Domain Events with the Read Model
Understand how to use middleware to publish domain events.
Running the application now with all the changes in place for the Store Management module, we will see the following appear in the logs when we add a new product:
started mallbots applicationweb server started; listening at http://localhost:8080rpc server startedINF --> Stores.GetStoresINF <-- Stores.GetStoresINF --> Stores.AddProductINF <-- Stores.AddProduct
Assuming everything is wired up correctly, and the handler access logging is set to log all HandleEvent()
calls, this might seem a little confusing. There should be some additional lines in there that show the HandleEvent()
method on CatalogHandlers
was accessed. What we should be seeing is this:
started mallbots applicationweb server started; listening at http://localhost:8080rpc server startedINF --> Stores.GetStoresINF <-- Stores.GetStoresINF --> Stores.AddProductINF --> Stores.Catalog.On(stores.ProductAdded)INF <-- Stores.Catalog.On(stores.ProductAdded)INF <-- Stores.AddProduct
There is a simple explanation for why we do not see the event being handled. The reason we do not see the extra lines signaling to us that the CatalogHandlers
implementation received the stores.ProductAdded
event is that by the time the domain event publisher gets a hold of the product aggregate, the events have already been committed and cleared from it. Here are the important lines from the AddProduct
command handler:
// ...if err = h.products.Save(ctx, product); err != nil {return err }if err = h.domainPublisher.Publish(ctx, product.GetEvents()...,); err != nil {return err}// ...
Recall that the third step for the Save()
method on AggregateRepository
is to update the aggregate version and clear the events using the aggregate.CommitEvents()
...