From e5396554c40a7676c320f3252819706b75f2d534 Mon Sep 17 00:00:00 2001 From: Deepak Bhat Date: Mon, 1 Mar 2021 21:36:42 +0530 Subject: [PATCH] upgraded hset to be the same as hmset --- lib/server/hash.js | 45 ++++++++++++++++++++++++----- test/client/redis-mock.hash.test.js | 12 ++++++++ 2 files changed, 50 insertions(+), 7 deletions(-) diff --git a/lib/server/hash.js b/lib/server/hash.js index 4d0044d..0b6c59e 100644 --- a/lib/server/hash.js +++ b/lib/server/hash.js @@ -98,24 +98,55 @@ exports.hdel = function (hash) { /* * Hset */ -exports.hset = function (hash, key, value, callback) { +exports.hset = function (hash) { + + // We require at least 3 arguments + // 0: mockInstance + // 1: hash name + // 2..N-2: key + // 3..N-1: value + // N: callback (optional) + var update = false; + let count = 0; + var len = arguments.length; + if (len <= 2) { + return; + } + var callback; + if ('function' === typeof arguments[len - 1]) { + callback = arguments[len-1]; + } + + // check to see if this hash exists if (this.storage[hash]) { - if (this.storage[hash].type !== "hash") { + if (this.storage[hash].type !== "hash" && callback) { return helpers.callCallback(callback, new Error("ERR Operation against a key holding the wrong kind of value")); } - if (this.storage[hash].value[key]) { - update = true; - } } else { this.storage[hash] = Item.createHash(); } - this.storage[hash].value[key] = value.toString(); + for (var i = 1; i < len; i += 2) { + if (len <= (i + 1)) { + // should skip the callback here + break; + } + var k = arguments[i]; + var v = arguments[i + 1]; + + if (this.storage[hash].value[k]) { + update = true; + } + this.storage[hash].value[k] = v.toString(); + count++; + } - helpers.callCallback(callback, null, update ? 0 : 1); + if (callback) { + helpers.callCallback(callback, null, update ? 0 : count); + } }; /** diff --git a/test/client/redis-mock.hash.test.js b/test/client/redis-mock.hash.test.js index 26f775d..49f6838 100644 --- a/test/client/redis-mock.hash.test.js +++ b/test/client/redis-mock.hash.test.js @@ -45,6 +45,18 @@ describe("basic hashing usage", function () { }); + it("should set multiple values", function (done) { + + r.hset(testHash, testKey, testValue, testKey + "2", testValue + "2", testKey + "3", testValue + "3", function (err, result) { + + result.should.equal(3); + + done(); + + }); + + }); + it("should treat empty string as existent", function (done) { r.hset(testHash, testKeyEmptyString, testValueEmptyString, function (err, result) { r.hexists(testHash, testKeyEmptyString, function (err, result) {