Code Monkey home page Code Monkey logo

evtstore's Introduction

EvtStore

Type-safe Event Sourcing and CQRS with Node.JS and TypeScript

Note: createDomain will be migrating to createDomainV2 in version 11.x The createDomainV2 API solves circular reference issues when importing aggregates. The original createDomain will be available as createDomainV1 from 11.x onwards.

Why

I reguarly use event sourcing and wanted to lower the barrier for entry and increase productivity for colleagues.
The design goals were:

  • Provide as much type safety and inference as possible
  • Make creating domains quick and intuitive
  • Be easy to test
  • Allow developers to focus on application/business problems instead of Event Sourcing and CQRS problems

To obtain these goals the design is highly opinionated, but still flexible.

Supported Databases

See Providers for more details and examples

Aggregate Persistence

See the documentation regarding information about aggregate persistence. This refers to persisting a copy of the aggregate on events for performant retrieval.

Examples

EvtStore is type-driven to take advantage of type safety and auto completion. We front-load the creation of our Event, Aggregate, and Command types to avoid having to repeatedly import and pass them as generic argument. EvtStore makes use for TypeScript's mapped types and conditional types to achieve this.

type UserEvt =
  | { type: 'created', name: string }
  | { type: 'disabled' }
  | { type: 'enabled' }
type UserAgg = { name: string, enabled: boolean }
type UserCmd =
  | { type: 'create': name: string }
  | { type: 'enable' }
  | { type: 'disable' }

type PostEvt =
  | { type: 'postCreated', userId: string, content: string }
  | { type: 'postArchived' }

type PostAgg = { userId: string, content: string, archived: boolean }
type PostCmd =
  | { type: 'createPost', userId: string, content: string }
  | { type: 'archivedPost', userId: string }

const user = createAggregate<UserEvt, UserAgg, 'users'>({
  stream: 'users',
  create: () => ({ name: '', enabled: false }),
  fold: (evt) => {
    switch (evt.type) {
      case 'created':
        return { name: evt.name, enabled: true }
      case 'disabled':
        return { enabled: false }
      case 'enabled':
        return { enabled: true }
    }
  }
})

const post = createAggregate<PostEvt, PostAgg, 'posts'>({
  stream: 'posts',
  create: () => ({ content: '', userId: '', archived: false }),
  fold: (evt) => {
    switch (evt.type) {
      case 'postCreated':
        return { userId: evt.userId, content: evt.content }
      case 'postArchived':
        return { archived: true }
    },
  }
})

const provider = createProvider()

export const { domain, createHandler } = createDomain({ provider }, { user, post })

export const userCmd = createCommands<UserEvt, UserEvt, UserCmd>(domain.user, {
  async create(cmd, agg) { ... },
  async disable(cmd, agg) { ... },
  async enable(cmd, agg) { ... },
})

export const postCmd = createCommands<PostEvt, PostAgg, PostCmd>(domain.post, {
  async createPost(cmd, agg) {
    if (agg.version) throw new CommandError('Post already exists')
    const user = await domain.user.getAggregate(cmd.userId)
    if (!user.version) throw new CommandError('Unauthorized')

    return { type: 'postCreated', content: cmd.content, userId: cmd.userId }
  },
  async archivePost(cmd, agg) {
    if (cmd.userId !== agg.userId) throw new CommandError('Not allowed')
    if (agg.archived) return

    return { type: 'postArchived' }
  }
})

const postModel = createHandler('posts-model', ['posts'], {
  // When the event handler is started for the first time, the handler will begin at the end of the stream(s) history
  tailStream: false,

  // Every time the event handler is started, the handler will begin at the end of the stream(s) history
  alwaysTailStream: false,

  // Skip events that throw an error when being handled
  continueOnError: false,
})

postModel.handle('posts', 'postCreated', async (id, event, meta) => {
  // Insert into database
})
postModel.start()

See the example folder

API

See API

evtstore's People

Contributors

dependabot[bot] avatar seikho avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

evtstore's Issues

How to copy an aggregate?

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.

How to pass transaction to be able to rollback a sequence of actions?

I am using the evtstore library in our app and I need a way to pass transaction in knex provider in order to rollback a sequence of actions in our application. Do you have any advice for it? After a small walkthrough in codebase it seems that I need to pass it only in the append function of the provider (where exists the only insertion in events table)

confusion around streams, aggregates and ids

Hi! Just found this nice little library that I'm now trying out ๐Ÿ‘
I started out with looking and toying with your sample code and tried to modify it so that a userId is passed around as well.
I'm a bit confused on what the aggregate should be. In my mind I would like to have a stream and aggregate per user (and perhaps also a stream for all users). If I want to build an aggregate per user; do I need a new domain for each user in this case? I'm new to event sourcing, so forgive me if the question is unclear or vague.

br Oskar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.