Skip to content

Commit

Permalink
refactor: use ioredis client
Browse files Browse the repository at this point in the history
  • Loading branch information
AndrewJo committed Dec 5, 2024
1 parent d387c17 commit 780d2a6
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 13 deletions.
32 changes: 23 additions & 9 deletions src/redis.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,14 @@
*/

import { Driver } from "@verdigris/nitrous";
import { RedisClientType, RedisClientOptions, createClient } from "redis";
import { default as _Redis, RedisOptions } from "ioredis";

export default class Redis extends Driver {
private _client: RedisClientType;
private _options: RedisClientOptions;
private _client: _Redis;
private _options: RedisOptions;
#closed: boolean;

public constructor(options?: RedisClientOptions) {
public constructor(options?: RedisOptions) {
super();
this._options = options;
}
Expand All @@ -20,10 +21,23 @@ export default class Redis extends Driver {
* not found error when importing this library without installing the redis
* package.
*/
public get client(): RedisClientType {
public get client(): _Redis {
// eslint-disable-next-line @typescript-eslint/no-this-alias
const self = this;

if (!this._client) {
this._client = createClient(this._options) as RedisClientType;
this._client.connect();
const onEnd = function () {
// Distinguish between whether connection closed due to user request.
self.#closed = true;

// Detach event listener once closed.
self._client.off("end", onEnd);
};

this._client = new _Redis(this._options).on("end", onEnd);
this._client.connect().then(() => {
this.#closed = false;
});
}

return this._client;
Expand All @@ -50,7 +64,7 @@ export default class Redis extends Driver {
}

private _setex(key: string, seconds: number, value: string): Promise<string> {
return this.client.setEx.bind(this.client)(key, seconds, value);
return this.client.setex.bind(this.client)(key, seconds, value);
}

private _ttl(key: string): Promise<number> {
Expand All @@ -66,7 +80,7 @@ export default class Redis extends Driver {
}

public get isClosed(): boolean {
return !this.client.isOpen;
return this.#closed;
}

public async isConnected(): Promise<boolean> {
Expand Down
6 changes: 2 additions & 4 deletions tests/test-redis.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,8 @@ import { sleep } from "@tests/util";

function getDriver(): Redis {
return new Redis({
socket: {
host: process.env.REDIS_HOST ?? "127.0.0.1",
port: +process.env.REDIS_PORT || 6379,
},
host: process.env.REDIS_HOST ?? "127.0.0.1",
port: +process.env.REDIS_PORT || 6379,
});
}

Expand Down

0 comments on commit 780d2a6

Please sign in to comment.