@nodeject/event-sourcing
v0.0.1-beta.1499608825
Published
Event sourcing
Downloads
8
Readme
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;