Skip to content

Commit

Permalink
Remove redis events on connection end (#880)
Browse files Browse the repository at this point in the history
* Remove redis events on connection end

* Fix the on and off events from connection eventListeners

Co-authored-by: Juan M <[email protected]>
  • Loading branch information
joksnet and jm42 authored Nov 9, 2022
1 parent 26379a5 commit 10e11e6
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 5 deletions.
11 changes: 11 additions & 0 deletions __tests__/core/connection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -159,4 +159,15 @@ describe("connection", () => {
expect(connection.key("thing")).toBe("thing");
connection.end();
});

test("removes the redis event listeners when end", async () => {
const connectionDetails = specHelper.cleanConnectionDetails();
const connection = new Connection(connectionDetails);
await connection.connect();
expect(connection.redis.listenerCount("error")).toBe(1);
expect(connection.redis.listenerCount("end")).toBe(1);
connection.end();
expect(connection.redis.listenerCount("error")).toBe(0);
expect(connection.redis.listenerCount("end")).toBe(0);
});
});
11 changes: 6 additions & 5 deletions src/core/connection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import * as path from "path";
import { ConnectionOptions } from "..";

interface EventListeners {
[key: string]: Function;
[key: string]: (...args: any[]) => void;
}

export class Connection extends EventEmitter {
Expand Down Expand Up @@ -75,8 +75,9 @@ export class Connection extends EventEmitter {
this.eventListeners.end = () => {
this.connected = false;
};
this.redis.on("error", (err) => this.eventListeners.error(err));
this.redis.on("end", () => this.eventListeners.end());
Object.entries(this.eventListeners).forEach(([eventName, eventHandler]) => {
this.redis.on(eventName, eventHandler);
});

if (!this.options.redis && typeof this.redis.select === "function") {
await this.redis.select(this.options.database);
Expand Down Expand Up @@ -141,8 +142,8 @@ export class Connection extends EventEmitter {
}

end() {
Object.keys(this.listeners).forEach((eventName) => {
this.redis.removeAllListeners(eventName);
Object.entries(this.eventListeners).forEach(([eventName, eventHandler]) => {
this.redis.off(eventName, eventHandler);
});

// Only disconnect if we established the redis connection on our own.
Expand Down

0 comments on commit 10e11e6

Please sign in to comment.