From 95c0e7d5d0124666b6841a75ff7495ecaa64e825 Mon Sep 17 00:00:00 2001 From: Anatoliy Chakkaev Date: Fri, 23 Mar 2012 00:24:15 +0400 Subject: [PATCH] upsert for redis --- lib/adapters/redis.js | 15 ++++++++++----- test/common_test.js | 3 ++- 2 files changed, 12 insertions(+), 6 deletions(-) diff --git a/lib/adapters/redis.js b/lib/adapters/redis.js index cdfbd7e0..32724508 100644 --- a/lib/adapters/redis.js +++ b/lib/adapters/redis.js @@ -67,7 +67,7 @@ BridgeToRedis.prototype.updateIndexes = function (model, id, data, callback) { if (schedule.length) { this.client.multi(schedule).exec(function (err) { - callback(err); + callback(err, data); }); } else { callback(null); @@ -75,9 +75,15 @@ BridgeToRedis.prototype.updateIndexes = function (model, id, data, callback) { }; BridgeToRedis.prototype.create = function (model, data, callback) { + if (data.id) return create.call(this, data.id, true); + var log = this.logger('INCR id:' + model); this.client.incr('id:' + model, function (err, id) { log(); + create.call(this, id); + }.bind(this)); + + function create(id, upsert) { data.id = id; this.save(model, data, function (err) { if (callback) { @@ -87,9 +93,8 @@ BridgeToRedis.prototype.create = function (model, data, callback) { // push the id to the list of user ids for sorting log('SADD s:' + model + ' ' + data.id); - this.client.sadd("s:" + model, data.id); - - }.bind(this)); + this.client.sadd("s:" + model, upsert ? data : data.id); + } }; BridgeToRedis.prototype.exists = function (model, id, callback) { @@ -106,7 +111,7 @@ BridgeToRedis.prototype.find = function find(model, id, callback) { var t1 = Date.now(); this.client.hgetall(model + ':' + id, function (err, data) { this.log('HGETALL ' + model + ':' + id, t1); - if (data && data.id) { + if (data && Object.keys(data).length > 0) { data.id = id; } else { data = null; diff --git a/test/common_test.js b/test/common_test.js index 8e5ae72e..8f826e47 100644 --- a/test/common_test.js +++ b/test/common_test.js @@ -37,8 +37,9 @@ Object.keys(schemas).forEach(function (schemaName) { }); schema.log = function (a) { - // console.log(a); + console.log(a); }; + testOrm(schema); if (specificTest[schemaName]) specificTest[schemaName](schema); });