UNPKG

osr

Version:

osr

71 lines (64 loc) 2.23 kB
var redis = require("redis"); var Schema = require("../schema"); var RedisMQ = function(options){ this.options = options; this.port = options.port || 6379; this.host = options.host || "localhost"; this.conn = redis.createClient(this.port,this.host); this.lisconn = redis.createClient(this.port,this.host); if(options.index){ this.conn.select(options.index); this.lisconn.select(options.index); } this.schemas = {}; this.models = {}; this.collections = {}; } RedisMQ.prototype.define = function(name, model ,rename){ this.schemas[name] = new Schema(model.schema); this.models[name] = model; this.collections[name] = {publish:this.conn,subscribe:this.lisconn}; this.rename = rename||name; return this.models[name]; } RedisMQ.prototype.listen = function(cb){ var db = this.collections[this.name].subscribe; if(db){ db.subscribe(this.name,function(err,channel){ if(err){ cb(err); return; }else{ db.on("message",function(channel,message){ // console.log(channel,message); cb(JSON.parse(message),channel); }); } }) }else{ if(typeof(arguments[arguments.length-1]) == "function"){ arguments[arguments.length-1](new Error("RedisMQ:The "+this.name+" COLLECTION NOT FOUND")); } } } RedisMQ.prototype.publish = function(msg,cb){ var db = this.collections[this.name].publish; if(db){ cb(null,msg); if(typeof msg === "object"){ msg = JSON.stringify(msg); } // console.log("publish",this.name,msg); db.publish(this.name,msg); }else{ if(typeof(arguments[arguments.length-1]) == "function"){ arguments[arguments.length-1](new Error("RedisMQ:The "+this.name+" COLLECTION NOT FOUND")); } } } RedisMQ.prototype.connect = function(fn){ this.isconnected = true; // var db = this.collections[this.name]; // this.dao.listen.apply(this,this.listener); } module.exports = exports = RedisMQ;