UNPKG

osr

Version:

osr

91 lines (79 loc) 2.41 kB
var Schema = require("./schema"); var Model = function(name,schema,rename){ this.name = name; this.schema = new Schema(schema); this.rename = rename; this.dao = null; this.isconnected = false; this.listener = null; } Model.prototype.listen = function(cb){ this.listener = function(body,header){ cb(null,body); } if(!!this.isconnected){ this.dao.listen.call(this,this.listener); } } Model.prototype.publish = function(){ this.dao.publish.apply(this,arguments); } Model.prototype.parseToModel = function(obj){ var nObj = {}; for(var key in this.schema.schema){ if(obj[key]){ var type = this.schema.schema[key].type; if(typeof(type) === "object"||!type){ nObj[key] = JSON.parse(obj[key]); }else{ nObj[key] = obj[key]; } } } return nObj; } Model.prototype.findOne = function(){ return this.dao.findOne.apply(this,arguments); } Model.prototype.find = function(){ return this.dao.find.apply(this,arguments); } Model.prototype.create = function(obj,cb){ if((msg = this.schema.check(obj))!=null){ cb(msg); }else{ return this.dao.create.apply(this,arguments); } } Model.prototype.update = function(){ return this.dao.update.apply(this,arguments); } Model.prototype.connect = function(){ if(this.dao.connect) return this.dao.connect.apply(this,arguments); else return null; } Model.prototype.del = function(){ return this.dao.del.apply(this,arguments); } Model.prototype.inject = function(osr,options){ var dbType = options.dbType; var dbOptions = options; var key = dbType+"::"+JSON.stringify(dbOptions); if(!osr.daoList[key]){ osr.daoList[key] = new osr.Dao(dbType,dbOptions).getConn(); } osr._models[this.name] = osr.daoList[key].define(this.name,this,this.rename||this.name); this.dao = osr.daoList[key]; this.collections = this.dao.collections; this.schemas = this.dao.schemas; this.options = this.dao.options; this.db = this.collections[this.name]; this.connect(); } Model.prototype.setCollection = function(name){ this.db = this.dao.define(this.name,this,name); return this; } module.exports = exports = Model;