@@ -211,6 +211,8 @@ func (s *EventStore) Save(ctx context.Context, events []eh.Event, originalVersio
211
211
return nil
212
212
}
213
213
214
+ var handleEvents bool
215
+
214
216
// Run the operation in a transaction if using an outbox, otherwise it's not needed.
215
217
if s .eventHandlerInTX != nil {
216
218
if err := s .database .CollectionExecWithTransaction (ctx , s .collectionName , func (txCtx mongo.SessionContext , c * mongo.Collection ) error {
@@ -225,12 +227,6 @@ func (s *EventStore) Save(ctx context.Context, events []eh.Event, originalVersio
225
227
}
226
228
}
227
229
228
- for i := range events {
229
- if err := s .eventHandlerInTX .HandleEvent (ctx , events [i ]); err != nil {
230
- return fmt .Errorf ("could not handle event in transaction: %w" , err )
231
- }
232
- }
233
-
234
230
return nil
235
231
}); err != nil {
236
232
return & eh.EventStoreError {
@@ -242,6 +238,8 @@ func (s *EventStore) Save(ctx context.Context, events []eh.Event, originalVersio
242
238
Events : events ,
243
239
}
244
240
}
241
+
242
+ handleEvents = true
245
243
} else {
246
244
if err := s .database .CollectionExec (ctx , s .collectionName , func (ctx context.Context , c * mongo.Collection ) error {
247
245
dummySessionCtx := mongo .NewSessionContext (ctx , nil )
@@ -263,6 +261,14 @@ func (s *EventStore) Save(ctx context.Context, events []eh.Event, originalVersio
263
261
}
264
262
}
265
263
264
+ if handleEvents {
265
+ for i := range events {
266
+ if err := s .eventHandlerInTX .HandleEvent (ctx , events [i ]); err != nil {
267
+ return fmt .Errorf ("could not handle event in transaction: %w" , err )
268
+ }
269
+ }
270
+ }
271
+
266
272
// Let the optional event handler handle the events.
267
273
if s .eventHandlerAfterSave != nil {
268
274
for _ , e := range events {
0 commit comments