@nodeject/event-sourcing

0.0.1-beta.1499608825 • Public • Published

Event sourcing

Use for representing event sourced entities.

Bank account example

import {
    EventSourcedObject
} from '../src/event-sourcing';

class DepositCommand {
    constructor(amount) {
        this.amount = amount;
    }
}

class WithdrawCommand {
    constructor(amount) {
        this.amount = amount;
    }
}

class BankAccount extends AggregateRoot {
    constructor(id, balance, ...args) {
        super(id, ...args);

        this.balance = balance || 0;

        this.on(DepositCommand, (e) => this.balance += e.amount);
        this.on(WithdrawCommand, (e) => this.balance -= e.amount);

        this.validatorFor(DepositCommand, (e) => {
            if (e.amount < 0)
                throw Error('Cannot deposit negative amounts');
        })
        this.validatorFor(WithdrawCommand, (e) => {
            if (e.amount < 0)
                throw Error('Cannot withdraw negative amounts');
            if (e.amount > this.balance)
                throw Error('Not enough funds');
        });
    }    
}

Create an account

const account = new BankAccount('some-id', balance, { userId: someUserId });

Deposit

account.execute(new DepositCommand(10));

Withdraw

account.execute(new WithdrawCommand(10));

Explore changes

const id = account.id;

const changes = account.uncommittedEvents;

Dependencies (5)

Dev Dependencies (0)

    Package Sidebar

    Install

    npm i @nodeject/event-sourcing

    Weekly Downloads

    4

    Version

    0.0.1-beta.1499608825

    License

    MIT

    Last publish

    Collaborators

    • gregoryforel
    • scaredfinger
    • nodeject-admin