12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455 |
- import redis, { ClientOpts, RedisClient } from 'redis';
- import util from 'util';
- import consola from 'consola';
- const promisify = util.promisify;
- class Redis {
- _options: ClientOpts = {};
-
- isUseRedis = false;
- client: RedisClient | null;
- constructor(options: ClientOpts) {
- this._options = options;
- const client = this.initClient(options);
- this.client = client;
- }
- initClient(options: ClientOpts): RedisClient {
-
- const client = redis.createClient(options);
- client.on('error', err => {
- consola.error(err);
- });
- client.on('ready', () => {
- consola.success('redis is ready');
- this.init(client);
- });
- client.on('connect', () => {
- consola.success('redis is connected');
- this.isUseRedis = true;
- });
- client.on('reconnecting', () => {
- consola.warn('redis is reconnecting...');
- });
- client.on('end', () => {
- consola.warn('redis is closed');
- });
- return client;
- }
- get = (key: string): Promise<string | null> | undefined =>
- this.client?.get && promisify(this.client.get).bind(this.client)(key)
- set = (key: string, value: string): Promise<unknown> | undefined =>
- this.client?.set && promisify(this.client.set).bind(this.client)(key, value)
- setex = (key: string, ttl: number, value: string): Promise<unknown> | undefined =>
- this.client?.setex && promisify(this.client.setex).bind(this.client)(key, ttl, value)
- init(client: redis.RedisClient): void {
-
- this.get = (key) => promisify(client.get).bind(this.client)(key);
- this.set = (key, value) => promisify(client.set).bind(this.client)(key, value);
- this.setex = (key, ttl, value) => promisify(client.setex).bind(this.client)(key, ttl, value);
- }
- }
- export default Redis;
|