Seikho / evtstore

Event Sourcing and CQRS with Node.js and TypeScript
https://seikho.github.io/evtstore
63 stars 5 forks source link

How to copy an aggregate? #9

Closed oskbor closed 2 years ago

oskbor commented 2 years ago

I've stumbled a bit further and encountered my next problem. How do I go about copying an aggregate? I have a Presentation and then the command is issued to copy it (with a new aggregateId). image

I however haven't found a way to query for another aggregate from the command handler 🤔 So I'm unsure on how to get the extra data needed into the event. Perhaps there is another way to accomplish what I'm after.

best regards Oskar

Edit: typescript complains that I'm referencing the presentationDomain from inside itself, which is not legal.

Seikho commented 2 years ago

Apologies for the really slow reply! This has been a bit of a pain point for a while and I've just released an improved API to avoid this exact issue. The createDomainV2 API (or createDomain in version 11+) solves this by creating aggregates and command handlers separately.

It currently looks like:

Aggregates


// These would be created in their own modules for neatness:
const presentation = createAggregate<PresentationEvt, PresentationAgg, 'presentation'>({ stream: 'presentation', create, fold })
const another = createAggregate<AnotherEvt, AnotherAgg, 'another'>({ stream: 'another', create, fold })

export const { domain, createHandler } = createDomain({ provider }, { presentation, another })


> Commands
```ts
export const presentationCmd = createCommands<PresentationEvt, PresentationAgg, PresentationCmd>(domain.presentation, {
  copy: async (cmd, agg) => {
    if (agg.version !== 0) ...
    // This is now allowed because domains/aggregates are definitely created and available separately
    const source = await domain.presentation.getAggregate(cmd.sourceId)
  }
})

Because of these changes you can safely import domain safely wherever you need to in your app and in any command handler. Retrieving aggregates across command handlers is now safe.

Complete documentation and a small example is now available at https://seikho.github.io/evtstore