Skip to content

Commit

Permalink
feat: add mode property to client (#1618)
Browse files Browse the repository at this point in the history
Adds a .mode getter to the client that reports whether the client is
in 'normal', 'subscriber', or 'monitor' mode.
  • Loading branch information
joelrbrandt authored Jul 11, 2022
1 parent 5c989e5 commit 9e6db7d
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 0 deletions.
14 changes: 14 additions & 0 deletions lib/Redis.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*
Expand Down
12 changes: 12 additions & 0 deletions test/functional/monitor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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) => {
Expand Down
20 changes: 20 additions & 0 deletions test/functional/pub_sub.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 () {
Expand All @@ -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();
Expand Down

0 comments on commit 9e6db7d

Please sign in to comment.