2022-08-08 15:52:56 +02:00
|
|
|
/*
|
|
|
|
* Copyright (C) Sapphirecode - All Rights Reserved
|
|
|
|
* This file is part of Auth-Server-Helper which is released under MIT.
|
|
|
|
* See file 'LICENSE' for full license details.
|
|
|
|
* Created by Timo Hocker <timo@scode.ovh>, August 2022
|
|
|
|
*/
|
|
|
|
|
|
|
|
import IORedis from 'ioredis';
|
2022-08-10 16:18:05 +02:00
|
|
|
import { debug } from './debug';
|
2022-08-08 15:52:56 +02:00
|
|
|
|
2022-08-10 16:18:05 +02:00
|
|
|
const logger = debug ('redis');
|
2022-08-08 15:52:56 +02:00
|
|
|
|
|
|
|
export class Redis {
|
|
|
|
private _redis: IORedis | null = null;
|
|
|
|
|
2022-08-10 16:18:05 +02:00
|
|
|
public connect (url: string): void {
|
|
|
|
const log = logger.extend ('connect');
|
|
|
|
log ('connecting to redis instance %s', url);
|
2022-08-08 15:52:56 +02:00
|
|
|
if (this._redis !== null) {
|
2022-08-10 16:18:05 +02:00
|
|
|
log ('disconnecting existing redis client');
|
|
|
|
this.disconnect ();
|
2022-08-08 15:52:56 +02:00
|
|
|
}
|
|
|
|
|
2022-08-10 16:18:05 +02:00
|
|
|
this._redis = new IORedis (url);
|
|
|
|
this._redis.on ('connect', () => {
|
|
|
|
log ('connected');
|
2022-08-08 15:52:56 +02:00
|
|
|
});
|
2022-08-10 16:18:05 +02:00
|
|
|
this._redis.on ('ready', () => {
|
|
|
|
log ('ready');
|
2022-08-08 15:52:56 +02:00
|
|
|
});
|
2022-08-10 16:18:05 +02:00
|
|
|
this._redis.on ('error', (err) => {
|
|
|
|
log ('error %o', err);
|
2022-08-08 15:52:56 +02:00
|
|
|
});
|
2022-08-10 16:18:05 +02:00
|
|
|
this._redis.on ('reconnecting', () => {
|
|
|
|
log ('reconnecting');
|
2022-08-08 15:52:56 +02:00
|
|
|
});
|
2022-08-10 16:18:05 +02:00
|
|
|
this._redis.on ('end', () => {
|
|
|
|
log ('connection ended');
|
2022-08-08 15:52:56 +02:00
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2022-08-10 16:18:05 +02:00
|
|
|
public disconnect (): void {
|
|
|
|
const log = logger.extend ('disconnect');
|
|
|
|
log ('disconnecting redis client');
|
2022-08-08 15:52:56 +02:00
|
|
|
if (this._redis === null) {
|
2022-08-10 16:18:05 +02:00
|
|
|
log ('redis is inactive, skipping');
|
2022-08-08 15:52:56 +02:00
|
|
|
return;
|
|
|
|
}
|
2022-08-10 16:18:05 +02:00
|
|
|
this._redis.quit ();
|
2022-08-08 15:52:56 +02:00
|
|
|
this._redis = null;
|
2022-08-10 16:18:05 +02:00
|
|
|
log ('done');
|
2022-08-08 15:52:56 +02:00
|
|
|
}
|
|
|
|
|
2022-08-27 16:39:07 +02:00
|
|
|
protected get redis (): IORedis {
|
2022-08-15 17:33:25 +02:00
|
|
|
if (this._redis === null)
|
|
|
|
throw new Error ('redis is not connected');
|
|
|
|
|
|
|
|
return this._redis;
|
2022-08-08 15:52:56 +02:00
|
|
|
}
|
|
|
|
|
2022-08-27 16:39:07 +02:00
|
|
|
protected get is_active (): boolean {
|
2022-08-15 17:33:25 +02:00
|
|
|
return this._redis !== null;
|
2022-08-08 15:52:56 +02:00
|
|
|
}
|
|
|
|
}
|