event-sourced

An event sourced base class

npm install event-sourced
1 downloads in the last week
4 downloads in the last month

EventSourced

An event sourced base class.

Example:

var EventSourced = require('eventSourced').EventSourced;
var util = require('util');

var User = (function () {
    function User() {
        User.super_.apply(this, arguments);
    }

    util.inherits(User, EventSourced);

    // Commands
    User.prototype.create = function (value) {
        if (this._isCreated()) {
            this._handle("_notCreated", { reason: "User already exists" });
            return;
        }

        this._handle("_created");
        this._handle("_modified", { name: value.name });
    };

    User.prototype.modify = function (value) {
        if (!this._isCreated()) {
            this._handle("_notModified", { reason: "User does not exist" });
            return;
        }

        this._handle("_modified", value);
    };

    User.prototype["delete"] = function (value) {
        if (!this._isCreated()) {
            this._handle("_notModified", { reason: "User does not exist" });
            return;
        }

        this._handle("_deleted");
    };

    // Validation
    User.prototype._isCreated = function (callback) {
        return this._memento.created;
    };

    // Events
    User.prototype._created = function (value) {
        this._memento.created = true;
    };

    User.prototype._deleted = function (value) {
        this._memento.created = false;
    };

    return User;
})();

var user = new User("1");
user.on('committed', function (events, memento) {
    console.log('committed\r'
        + 'events:\r' + JSON.stringify(events, null, 2) + '\r\r'
        + 'memento:\r' + JSON.stringify(memento, null, 2) + '\r\r'
    );
});

user.create({name:"A"});
user.modify({name:"B"});
user.create({name:"C"});
user.commit();
user.commit();
user.delete();
user.create({name:"C"});
user.commit();
npm loves you