UNPKG

dl

Version:

DreamLab Libs

84 lines (68 loc) 2.7 kB
var Class = require("core").Class; var assertions = require("core").common.assertions; var types = require("core").common.types; var Memcache = require('./CFMemcache.js').CFMemcache; var MMemcache = function () { this.Extends = Memcache; this.initialize = function (options) { this.parent(options); this._storage = {}; this._expire = {}; this._lifetime = 30; }; this.getTimestamp = function () { return (+ new Date()); }; this.get = function (key, callback) { assertions.isString(key, MMemcache.Exception.WRONG_TYPE); var that = this; if (this._storage.hasOwnProperty(key)) { if (this.getTimestamp() >= this._expire[key] ) { console.log(' -- CACHE: key: ' + key + ' expired!'); delete this._expire[ key ]; delete this._storage[ key ]; this.parent(key, function (data) { // jezeli nie przyszedl null to zachesuj u mnie na chwile if (data) { console.log(data.length); that._storage[key] = data; that._expire[key] = that.getTimestamp() + (that._lifetime*1000); } callback(data); }); } else { process.nextTick(function () { callback(that._storage[key]); }); } } else { this.parent(key, function (data) { that._storage[key] = data; callback(data); }); } }; this.set = function (key, value, callback, lifeTime) { assertions.isString(key, MMemcache.Exception.WRONG_TYPE); lifeTime = lifeTime || this._lifetime; if (Buffer.isBuffer(value)) { this._storage[key] = value; } else { this._storage[key] = new Buffer(value, 'utf8'); } // u siebie zapisuje w ms a nie w sekundach this._expire[key] = this.getTimestamp() + (lifeTime * 1000); this.parent(key, value, callback, lifeTime); }; this['delete'] = function(key, callback){ assertions.isString(key, MMemcache.Exception.WRONG_TYPE); delete this._storage[key]; delete this._expire[key]; }; }; MMemcache = new Class(new MMemcache()); MMemcache.Exception = {}; MMemcache.Exception.WRONG_KEY_TYPE = "Key has to be a string"; MMemcache.Exception.WRONG_VALUE_TYPE = "Value has to be a string, number or object"; MMemcache.Exception.WRONG_LIFETIME_TYPE = "Lifetime has to be a number"; exports.MMemcache = MMemcache;