A question regarding use cases and database transactions
See original GitHub issueI’m sorry if this isn’t the right place to ask such a question, I’ve searched for hours everywhere and cannot seem to find an answer.
If i have a use case that fetches a two aggregates of different types from their repositories, and passes them to a domain service that preforms business logic on the aggregates and returns them to the use case, how would i save all the aggregates back to the database in a single transaction ?.
one solution i came up with is to have one of the repositories methods take the second aggregate as an argument to include in the database transaction:
interface IMemberRepo {
upgradeMemberToGold: (member: Member, payment: Payment) => Promise<void>
}
// or
interface IPaymentRepo {
markPaymentAsFulfilled: (payment: Payment, member: Member) => Promise<void>
}
if a member aggregate gets upgraded to gold there must be a payment aggregate with fulfilled: true
that exists, the above solution works but I’m not sure if it 100% adheres to DDD principles.
Issue Analytics
- State:
- Created 2 years ago
- Reactions:1
- Comments:5 (3 by maintainers)
Top GitHub Comments
Here is my implementation:
this.unitOfWork.execute
Edit: UnitOfWork refactored to support
correlationId
. This is needed to use different query runners for each request, otherwise query fails if there is a lot of concurrent requests since before they all used the same connection pool.There can be multiple ways of implementing it depending on your database sdk/orm. I’d try to do it as generic as possible to be able to reuse it:
With
add()
method you can add any amount of entities at any point, put them somewhere in an array internally, and then when you callcommit()
it just saves everything at once.Edit: sorry, the solution above is based on my other project which uses Event Sourcing and there is no need to include reads in the transaction there so it will not work for you I guess 😃 if you want to include reads in the transaction, returning repositories seems like a good solution