cqrs

cqrs for javascript

API DOC

Install

npm install cqrs --save

Test

npm test

Use

var Domain = require("cqrs").Domain;
var Actor = require("cqrs").Actor;
var domain = new Domain(options);  // create a cqrs domain
// use es5 extend tool
var extend = require("cqrs").extend;    
var User = extend({

   type:'User',
   
   init(data){
       data.name = '';
       data.accessNum = 0;
   },
   
   when:function(event){
       switch(event.name){
           case "changeName":
               this._data.name = event.name;
           break;
       }
   },

   changeName:function(name){
       this.apply("changeName",name);
   }
});


--- or use es6 class ---

class User extends Actor{

    static get type(){
       return 'User';
    }
    
    constructor(data){
        super({
            name;'',
            accessNum:0
        });
    }

    when(event){
        switch(event.name){
            case "changeName":
                this._data.name = event.name;
            break;
        }
    }

    changeName(name){
        this.apply("changeName",name);
    }
    
    access(){
        this.apply("access");
    }

}
domain.register(User);
domain.on("User.changeName",function(event){
    // ......
})
// create a user
domain.create("User",{name:"leo"},function(err,userId){
    ......
});


// get a user object
domain.get("User",userId,function(err,actor){

});

// or

domain.get("User",userId).then(function(actor){
    actor.changeName("leo giese");
});

// or

domain.call('User',userId,'changeName',['leo giese']);  // return a promise object
domain.call(`User.${userId}.changeName`,['leo giese']); 
domain.call(['User',userId,'changeName'],['leo giese']);
domain.call(`User.${userId}.changeName`,['leo giese'],function(err,result){ ... });

// if no need arguments
domain.call('User',userId,'access'); 
domain.call('User.${userId}.access'); 
domain.call(['User',userId,'access']); 

Advanced Usage

export default
class Transfer extends Actor {

    static get type() {
        return "Transfer";
    }

    transfer(fromId, toId, money) {
        ......

        this.listen("User." + fromId + ":deduct&" + this.id, "__userDeduct");
        this.listen("User." + toId + ":recharge&" + this.id, "__userRecharge");

        ......
    }

    // event handle method
    __userDeduct(event) {
        ......
    }

    __userRecharge(event) {
        ......
    }

}

LICENSE

MIT