diff --git a/lib/Redis.ts b/lib/Redis.ts index 7802ddeb..fdd5a6c8 100644 --- a/lib/Redis.ts +++ b/lib/Redis.ts @@ -338,6 +338,20 @@ class Redis extends Commander { return new Redis({ ...this.options, ...override }); } + /** + * Mode of the connection. + * + * One of `"normal"`, `"subscriber"`, or `"monitor"`. When the connection is + * not in `"normal"` mode, certain commands are not allowed. + */ + get mode(): "normal" | "subscriber" | "monitor" { + return this.options.monitor + ? "monitor" + : this.condition.subscriber + ? "subscriber" + : "normal"; + } + /** * Listen for all requests received by the server in real time. * diff --git a/test/functional/monitor.ts b/test/functional/monitor.ts index 0cc34e2d..05d4d18d 100644 --- a/test/functional/monitor.ts +++ b/test/functional/monitor.ts @@ -41,6 +41,18 @@ describe("monitor", () => { }); }); + it("should report being in 'monitor' mode", (done) => { + const redis = new Redis(); + redis.monitor(async (err, monitor) => { + await waitForMonitorReady(monitor); + expect(redis.mode).to.equal("normal"); + expect(monitor.mode).to.equal("monitor"); + redis.disconnect(); + monitor.disconnect(); + done(); + }); + }); + it("should continue monitoring after reconnection", (done) => { const redis = new Redis(); redis.monitor((err, monitor) => { diff --git a/test/functional/pub_sub.ts b/test/functional/pub_sub.ts index d8652093..0d4b6519 100644 --- a/test/functional/pub_sub.ts +++ b/test/functional/pub_sub.ts @@ -29,6 +29,15 @@ describe("pub/sub", function () { }); }); + it("should report being in 'subscriber' mode when subscribed", (done) => { + const redis = new Redis(); + redis.subscribe("foo", function () { + expect(redis.mode).to.equal("subscriber"); + redis.disconnect(); + done(); + }); + }); + it("should exit subscriber mode using unsubscribe", (done) => { const redis = new Redis(); redis.subscribe("foo", "bar", function () { @@ -52,6 +61,17 @@ describe("pub/sub", function () { }); }); + it("should report being in 'normal' mode after unsubscribing", (done) => { + const redis = new Redis(); + redis.subscribe("foo", "bar", function () { + redis.unsubscribe("foo", "bar", function (err, count) { + expect(redis.mode).to.equal("normal"); + redis.disconnect(); + done(); + }); + }); + }); + it("should receive messages when subscribe a channel", (done) => { const redis = new Redis(); const pub = new Redis();