diff --git a/__tests__/core/connection.ts b/__tests__/core/connection.ts index df9ce072..16ff3ba6 100644 --- a/__tests__/core/connection.ts +++ b/__tests__/core/connection.ts @@ -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); + }); }); diff --git a/src/core/connection.ts b/src/core/connection.ts index a49ace0f..6e6dd332 100644 --- a/src/core/connection.ts +++ b/src/core/connection.ts @@ -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 { @@ -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); @@ -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.