From b34ef9c79ca28545fc21fdbdec1b8aba9ae76c7b Mon Sep 17 00:00:00 2001 From: Lam Nguyen Date: Mon, 28 Aug 2023 14:14:11 -0700 Subject: [PATCH] Replace redis by ioredis --- index.js | 12 +++++------- package.json | 2 +- test/test.js | 18 +++++++++++++----- 3 files changed, 19 insertions(+), 13 deletions(-) diff --git a/index.js b/index.js index 6e3d6a1..930466c 100644 --- a/index.js +++ b/index.js @@ -12,10 +12,11 @@ async function acquireLock (client, lockName, timeout, retryDelay, onLockAcquire const lockTimeoutValue = Date.now() + timeout + 1; try { - const result = await client.set(lockName, lockTimeoutValue, { - PX: timeout, - NX: true - }); + const result = await client.set(lockName, lockTimeoutValue, "NX") + if (result === null) { + throw new Error("Lock failed"); + } + await client.set(lockName, lockTimeoutValue, "PX", timeout) if (result === null) { throw new Error("Lock failed"); } @@ -26,9 +27,6 @@ async function acquireLock (client, lockName, timeout, retryDelay, onLockAcquire } function redisLock (client, retryDelay = DEFAULT_RETRY_DELAY) { - if(!(client && client.set && "v4" in client)) { - throw new Error("You must specify a v4 client instance of https://github.com/redis/node-redis"); - } async function lock (lockName, timeout = DEFAULT_TIMEOUT) { return new Promise(resolve => { if (!lockName) { diff --git a/package.json b/package.json index cddc1af..d5beade 100644 --- a/package.json +++ b/package.json @@ -14,7 +14,7 @@ "dependencies": {}, "devDependencies": { "mocha": "4.x", - "redis": "4.x", + "ioredis": "5.x", "should": "^13.x" }, "scripts": { diff --git a/test/test.js b/test/test.js index 26fe803..40a194d 100644 --- a/test/test.js +++ b/test/test.js @@ -1,6 +1,8 @@ -const should = require("should"), - redisClient = require("redis").createClient(), - lock = require("../index")(redisClient) +const should = require("should") +const Redis = require("ioredis") +const redisClient = new Redis(); +const lock = require("../index")(redisClient) + const delay = (fn, ms) => new Promise( res => setTimeout(async () => { @@ -11,7 +13,12 @@ const delay = (fn, ms) => new Promise( describe("redis-lock", function() { before(async () => { - await redisClient.connect(); + try { + await redisClient.connect(); + } + catch (err) { + // Ignore if redis have connected + } }) after(async () => { @@ -51,7 +58,8 @@ describe("redis-lock", function() { const completed = await lock("testLock"); // This should be called after 300 ms - (new Date() - start).should.be.above(300); + const timeout = (new Date()) - start + timeout.should.be.above(300); await completed(); }); });