osr
Version:
osr
117 lines (110 loc) • 3.66 kB
JavaScript
var redis = require("redis");
var Schema = require("../schema");
var Redis = function(options){
this.options = options;
this.port = options.port || 6379;
this.host = options.host || "localhost";
this.conn = redis.createClient(this.port,this.host);
if(options.index){
this.conn.select(options.index);
}
if(this.auth){
this.conn.auth(this.auth);
}
this.schemas = {};
this.models = {};
this.collections = {};
}
Redis.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];
}
Redis.prototype.find = function(condition,cb){
if(typeof condition == "function"){
cb = condition;
condition = {};
}
var _this = this;
var key = this.schema.getMainKey(this.rename||this.name,condition);
var db = this.collections[this.name];
if(db){
db.keys(key,function(err,keys){
if(!!err||!keys.length){
cb(err,keys);
return;
}
var _index = 0;
var result = [];
keys.forEach(function(item,index){
db.hgetall(item,function(err,objFind){
if(!!err){
cb(err);
return;
}
result.push(_this.parseToModel(objFind));
if(++index==keys.length){
cb(null,result);
}
});
});
});
}else{
if(typeof(arguments[arguments.length-1]) == "function"){
arguments[arguments.length-1](new Error("REDIS:The "+this.name+" COLLECTION NOT FOUND"));
}
}
}
Redis.prototype.findOne = function(condition,cb){
var key = this.schema.getMainKey(this.rename||this.name,condition);
var db = this.collections[this.name];
var _this = this;
if(db){
return db.hgetall(key,function(err,gObj){
if(!!err||!gObj){
cb(err,gObj);
}else{
cb(null,_this.parseToModel(gObj));
}
});
}else{
if(typeof(arguments[arguments.length-1]) == "function"){
arguments[arguments.length-1](new Error("REDIS:The "+this.name+" COLLECTION NOT FOUND"));
}
}
}
Redis.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){
db.hmset(key,value,function(err,msg){
if(!!err){
cb(err);
}else{
cb(err,value);
}
});
db.expire(key,this.options.expire||60*60*2);
return obj;
}else{
if(typeof(arguments[arguments.length-1]) == "function"){
arguments[arguments.length-1](new Error("REDIS:The "+this.name+" COLLECTION NOT FOUND"));
}
}
}
Redis.prototype.del = function(condition,cb){
var key = this.schemas.getMainKey(this.rename||this.name,condition);
var db = this.collections[this.name];
var _this = this;
if(db){
return db.del(key,cb);
}else{
if(typeof(arguments[arguments.length-1]) == "function"){
arguments[arguments.length-1](new Error('REDIS:The '+this.name+" COLLECTION NOT FOUND"));
}
}
}
module.exports = exports = Redis;