1 var comb = require("comb"),
  2         hitch = comb.hitch,
  3         dataset = require("../dataset"),
  4         Promise = comb.Promise,
  5         PromiseList = comb.PromiseList,
  6         Hive = require("hive-cache");
  7 
  8 
  9 var hive;
 10 var i = 0;
 11 
 12 var LOGGER = comb.logging.Logger.getLogger("moose.plugins.CachePlugin");
 13 /**
 14  * @class Adds in memory caching support for models.
 15  *
 16  * @example
 17  *
 18  * var MyModel = moose.addModel("testTable", {
 19  *     plugins : [moose.plugins.CachePlugin];
 20  * });
 21  *
 22  * //NOW IT WILL CACHE
 23  *
 24  * @name CachePlugin
 25  * @memberOf moose.plugins
 26  */
 27 exports.CachePlugin = comb.define(null, {
 28     instance : {
 29 
 30         constructor : function() {
 31             if(!hive) hive = new Hive();
 32             this.super(arguments);
 33             this.post("load", this._postLoad);
 34         },
 35 
 36         reload : function() {
 37             var ret = new Promise();
 38             this.super(arguments).then(hitch(this, function(m) {
 39                 cache.replace(m.table + m.primaryKeyValue, m);
 40                 ret.callback(m);
 41             }), hitch(ret, "errback"));
 42             return ret;
 43         },
 44 
 45         save : function() {
 46             return this.super(arguments);
 47         },
 48 
 49         _postLoad : function(next) {
 50             hive.replace(this.tableName + this.primaryKeyValue, this);
 51             next();
 52         },
 53 
 54         update : function(options, errback) {
 55             var ret = new Promise();
 56             this.super(arguments).then(hitch(this, function(val) {
 57                 hive.remove(this.table + this.primaryKeyValue, val);
 58                 ret.callback(val);
 59             }), hitch(ret, "errback"));
 60             return ret;
 61         },
 62 
 63         remove : function(errback) {
 64             hive.remove(this.primaryKeyValue);
 65             var ret = this.super(arguments);
 66             return ret;
 67         },
 68 
 69 
 70         getters : {
 71             tableName : function() {
 72                 return this.table.tableName;
 73             }
 74         }
 75 
 76     },
 77 
 78     static : {
 79 
 80         findById : function(id) {
 81             var cached = hive.get(this.tableName + id);
 82             if (!cached) {
 83                 LOGGER.debug("not CAHCED");
 84                 return this.super(arguments);
 85             } else {
 86                 var ret = new Promise();
 87                 ret.callback(cached);
 88                 return ret;
 89             }
 90         }
 91     }
 92 });