qas / examples-nodejs-cqrs-es-swagger

A Node.js CQRS and Event Sourcing Microservice Example Using Nest.js, Event Store, and Swagger
491 stars 141 forks source link

Another Aggregate Root #1

Open Jtosbornex opened 5 years ago

Jtosbornex commented 5 years ago

So far this is the most complete example of ddd+ event sourcing + cqrs I have seen for nest. Thank you 🙏

One thing I would like to see is how you handle more aggregate roots?

Do they each get their own folder like user?

Also as a side note I think user is a bit too all encompassing of a domain.

petervankleef commented 5 years ago

Hey, just felt like sharing my solution (which is probably not the best way possible 🤷‍♂ )..

I think each 'domain' should indeed get its own folder, like user.

Getting several of them working at the same time does requires a few changes to the event-store.ts file:

1. Remove the implementation of IMessageSource, i.e.:

Needed to do this because otherwise we can't add the extra parameter to bridgeEventsTo (see step 2)

export class EventStore implements IEventPublisher {

2. Add an extra parameter to the bridgeEventsTo method:

Need to make sure that we subscribe to the category of each module

async bridgeEventsTo<T extends IEvent>(subject: Subject<T>, category: string) {
const streamName = `$ce-${category}`;

3. change setEventHandlers to:

This is needed because you are now setting eventHandlers from several modules, and if you don't spread them then only the eventHandlers from the last module will be available.

setEventHandlers(eventHandlers) {
this.eventHandlers = {...this.eventHandlers, ...eventHandlers};
}

4. then in your modules (such as user.module.ts):

Making sure we are setting the category for the bridge to subscribe to

this.eventStore.bridgeEventsTo((this.event$ as any).subject$, 'users');

Note:

hope this helps 😃