|
1 | 1 | import { ClientSession, Collection, MongoClient, ObjectId } from 'mongodb'; |
2 | | -import { IEvent } from '../event-bus/event-bus.interface'; |
| 2 | +import { IEvent } from '../event-bus'; |
3 | 3 | import { ILogger } from '../logger'; |
4 | 4 | import { inspect } from 'util'; |
5 | 5 | import { difference, intersection } from 'lodash'; |
@@ -57,42 +57,7 @@ export class MongoOutbox implements IOutbox, IInit, ITerminate { |
57 | 57 | } |
58 | 58 |
|
59 | 59 | public async publishEvents(scheduledEventsIds: string[]): Promise<void> { |
60 | | - const session = this.mongoClient.startSession(); |
61 | | - try { |
62 | | - await session.withTransaction(async () => { |
63 | | - const outboxModels = await this.outboxCollection |
64 | | - .find( |
65 | | - { |
66 | | - _id: { $in: scheduledEventsIds.map((id) => new ObjectId(id)) }, |
67 | | - status: 'scheduled', |
68 | | - }, |
69 | | - { session }, |
70 | | - ) |
71 | | - .toArray(); |
72 | | - if (!outboxModels.length) return; |
73 | | - const events = outboxModels.map((model) => model.event); |
74 | | - await this.publishEventsFn(events); |
75 | | - const publishedIds = outboxModels.map((model) => model._id); |
76 | | - await this.outboxCollection.updateMany( |
77 | | - { |
78 | | - _id: { $in: publishedIds }, |
79 | | - status: 'scheduled', |
80 | | - }, |
81 | | - { |
82 | | - $set: { |
83 | | - status: 'published', |
84 | | - publishedAt: new Date(), |
85 | | - }, |
86 | | - }, |
87 | | - { session }, |
88 | | - ); |
89 | | - this.logger.debug(`Published events ${publishedIds.join(', ')}`); |
90 | | - }); |
91 | | - } catch (e) { |
92 | | - this.logger.warn(`Failed to publish events ${scheduledEventsIds.join(', ')}. ${inspect(e)}`); |
93 | | - } finally { |
94 | | - await session.endSession(); |
95 | | - } |
| 60 | + await Promise.all(scheduledEventsIds.map((eventId) => this.publishEventWithConcurrencyControl(eventId))); |
96 | 61 | } |
97 | 62 |
|
98 | 63 | //FROM https://github.com/gpad/ms-practical-ws/blob/main/src/infra/outbox_pattern.ts |
@@ -156,6 +121,8 @@ export class MongoOutbox implements IOutbox, IInit, ITerminate { |
156 | 121 | { session }, |
157 | 122 | ); |
158 | 123 | }); |
| 124 | + } catch (e) { |
| 125 | + this.logger.warn(`Failed to publish event ${eventId}. ${inspect(e)}`); |
159 | 126 | } finally { |
160 | 127 | await session.endSession(); |
161 | 128 | } |
|
0 commit comments