osr
Version:
osr
98 lines (90 loc) • 3.18 kB
JavaScript
var Stomp = require("stomp-client");
var Schema = require("../schema");
var MQ = function(options){
this.options = options;
this.port = options.port||61613;
this.host = options.host||"localhost";
this.user = options.user||"admin";
this.upass = options.upass||"admin";
console.log(this.host,this.port,this.user,this.upass);
this.conn = new Stomp(this.host,this.port,this.user,this.upass);
this.queue = "/queue/"+options.queue;
this.schemas = {};
this.models = {};
this.collections = {};
var _this = this;
}
MQ.prototype.connect = function(fn){
var db = this.collections[this.name];
var _this = this;
db.connect(function(sessionId){
console.log("connect",sessionId);
_this.isconnected = true;
if(fn){
fn(null,sessionId);
}
if(_this.listener){
db.subscribe(_this.dao.queue+"->"+_this.name,_this.listener);
}
if(_this.queArray){
while(_this.queArray){
var item = _this.queArray.shift()
db.create(item.value,item.cb);
}
}
});
}
MQ.prototype.define = function( name , model, rename){
this.schemas[name] = new Schema(model.schema);
this.models[name] = model;
this.collections[name] = this.conn;
this.rename = rename||name;
return this.models[name];
}
MQ.prototype.create = function(obj,cb){
var key = this.schema.getMainKey(this.name,obj);
var value = this.schema.getMainValue(this.name,obj);
var db = this.collections[this.name];
if(db){
if(!this.isconnected){
// this.queArray.push.call(MQ.prototype.queArray,{name:this.name,value:JSON.stringify(value)});
if(!this.queArray){
this.queArray = [];
}
cb(null,value)
return this.queArray.push({value:value,cb:cb});
}
cb(null,value);
return db.publish(this.dao.queue+"->"+this.name,JSON.stringify(value));
}else{
if(typeof(arguments[arguments.length-1]) == "function"){
arguments[arguments.length-1](new Error("MQ:The "+this.name+" COLLECTION NOT FOUND"));
}
}
}
MQ.prototype.findOne = function(condition,cb){
var _this = this;
var db = this.collections[this.name];
this.subCB = function(body,headers){
_this.unsubscribe(_this.queue+"->"+_this.name);
cb(null,JSON.parse(body));
};
if(db){
db.subscribe(this.queue+"->"+this.name,this.subCB);
}else{
if(typeof(arguments[arguments.length-1]) == "function"){
arguments[arguments.length-1](new Error("MQ:The "+this.name+" COLLECTION NOT FOUND"));
}
}
}
MQ.prototype.listen = function(cb){
var db = this.collections[this.name];
if(db){
db.subscribe(this.queue+"->"+this.name,cb);
}else{
if(typeof(arguments[arguments.length-1]) == "function"){
arguments[arguments.length-1](new Error("MQ:The "+this.name+" COLLECTION NOT FOUND"));
}
}
}
module.exports = exports = MQ;