UNPKG

rob

Version:
104 lines (94 loc) 3.21 kB
var redis = require("redis"); var Promise = require("bluebird"); var _ = require("lodash"); function AutosaveObject(key, attributes) { if ((typeof window !== "undefined" && this === window) || (typeof self !== "undefined" && this === self)) { throw new TypeError("Tried to call class AutosaveObject as a regular function. Classes can only be called with the 'new' keyword."); } this.redis = redis.createClient(); this.attributes = attributes || {}; if (key) { this.key = key; } else if (this.keyGenerator) { this.key = this.keyGenerator(); } else { this.key = Date.now() + Math.floor(Math.random() * 1000); } } AutosaveObject.prototype.attributes = {}; AutosaveObject.prototype.hashKey = 'autosaveobject'; AutosaveObject.prototype.get = function(key) { return this.attributes[key]; }; AutosaveObject.prototype.set = function(key, value) { this.attributes[key] = value; return this.save(); }; AutosaveObject.prototype.save = function() { var __scope_11__ = this; return new Promise(function(resolve, reject) { __scope_11__.redis.hset(__scope_11__.hashKey, __scope_11__.key, JSON.stringify(__scope_11__.attributes), function(err, res) { if (err) { reject(err); } resolve(res); }); }); }; AutosaveObject.prototype.toString = function() { return JSON.stringify(this.attributes); }; AutosaveObject.fetch = function(id, callback) { var __scope_28__ = this; var r = this.redis || redis.createClient(); constructor = this; return new Promise(function(resolve, reject) { if (id) { r.hget(__scope_28__.prototype.hashKey, id, function(err, res) { if (err) { reject(err); } if (res === null) { reject('No object for key: ' + id + ''); } var obj = new constructor(id, JSON.parse(res)); resolve(obj); callback && callback(obj); }); } else { r.hgetall(__scope_28__.prototype.hashKey, function(err, res) { if (err) { reject(err); } var output = []; var __a1 = Object.keys(res); var __l1 = __a1.length; for (var __i1 = 0; __i1 < __l1; __i1++) { var key = __a1[__i1]; output.push(new constructor(key, JSON.parse(res[key]))); } resolve(output); callback && callback(output); }); } }); }; AutosaveObject.extend = function(protoProps, staticProps) { var __scope_32__ = this; var child = function() { return __scope_32__.apply(this, arguments); }; _.extend(child, this, staticProps); var Surrogate = function() { this.constructor = child; }; Surrogate.prototype = this.prototype; child.prototype = new Surrogate; if (protoProps) { _.extend(child.prototype, protoProps); } return child; }; module.exports = { 'AutosaveObject': AutosaveObject };