Reputation: 3783
What are the options to validate an event which uses another model?
Shopping cart example:
When adding a cart item to the shopping cart, there should be a check if the item isn't sold out yet.
Upvotes: 0
Views: 114
Reputation: 5049
What are the options to validate an event which uses another model?
A domain event
is an important happening from the point of view of the business. It's something that happen in the past, so it can't be changed.
In OO, it's commonly represented as a Value Object
, that's say, an immutable object where the interesting part are their attributes.
Commonly, those Domain Events
are yield from an operation in a Aggregate Root
(DDD jargon). The client of the Aggregate Root
is the Application Service
(aka use case). The Application Service
receive a Command
object and base on that, executes operation in the Aggregate Root
.
The validation could consist in primitive validation, object validation and/or composed object validation. Then the object in charge to perform this validation should be the Aggregate Root
itself and/or some objects with the specific goal in validation.
When adding a cart item to the shopping cart, there should be a check if the item isn't sold out yet
Following your example the objects woulb be:
AddItemToShoppingCartCommand
. Holds information about the item to be added, and shopping cart identifier for example.AddItemToShoppingCartService
.ShoppingCartInventory
. I've used deliberately Inventory
in the name to be explicit that this Aggregate Root
satisfy the invariant "...if the item isn't sold out yet."Note: In my opinion, the invariant that checks the inventory in the Aggregate Root
, makes the Aggregate too big. My advice is relax this invariant and embrace eventual consistency if this "sold out" it's not happen normally.
Upvotes: 1
Reputation: 2369
You would usually validate a command rather than an event as an event should be something that cannot be changed
In answer to the question, typically it depends on what the business cost of the process is. In your example for instance, what is the cost to the business of ordering an item that is sold out? Probably very little - an email saying the item is out of stock, with an estimate of how long it will take.
In this type of scenario you could use an eventually consistent read model over the data, where you'd query the read model / cache for stock levels, but accept that some orders might go through for things that are out of stock.
If you have tighter constraints then you'll have to enforce them, ideally by remodelling your aggregates, or having transactional and/or blocking on the ordering process.
Upvotes: 4