@@ -4,16 +4,29 @@ import { BufferJSON } from '@whiskeysockets/baileys';
44import { Redis } from '../config/env.config' ;
55
66export class RedisCache {
7- constructor ( private readonly redisEnv : Partial < Redis > , private instanceName ?: string ) {
8- this . client = createClient ( { url : this . redisEnv . URI } ) ;
9-
10- this . client . connect ( ) ;
7+ constructor ( ) {
8+ process . on ( 'beforeExit' , async ( ) => {
9+ if ( this . statusConnection ) {
10+ await this . client . disconnect ( ) ;
11+ }
12+ } ) ;
1113 }
1214
15+ private statusConnection = false ;
16+ private instanceName : string ;
17+ private redisEnv : Redis ;
18+
1319 public set reference ( reference : string ) {
1420 this . instanceName = reference ;
1521 }
1622
23+ public async connect ( redisEnv : Redis ) {
24+ this . client = createClient ( { url : redisEnv . URI } ) ;
25+ await this . client . connect ( ) ;
26+ this . statusConnection = true ;
27+ this . redisEnv = redisEnv ;
28+ }
29+
1730 private readonly logger = new Logger ( RedisCache . name ) ;
1831 private client : RedisClientType ;
1932
@@ -35,6 +48,7 @@ export class RedisCache {
3548 public async writeData ( field : string , data : any ) {
3649 try {
3750 const json = JSON . stringify ( data , BufferJSON . replacer ) ;
51+
3852 return await this . client . hSet (
3953 this . redisEnv . PREFIX_KEY + ':' + this . instanceName ,
4054 field ,
@@ -51,6 +65,7 @@ export class RedisCache {
5165 this . redisEnv . PREFIX_KEY + ':' + this . instanceName ,
5266 field ,
5367 ) ;
68+
5469 if ( data ) {
5570 return JSON . parse ( data , BufferJSON . reviver ) ;
5671 }
@@ -79,20 +94,4 @@ export class RedisCache {
7994 this . logger . error ( error ) ;
8095 }
8196 }
82-
83- public async closeConnection ( ) {
84- try {
85- await this . client . quit ( ) ;
86- } catch ( error ) {
87- this . logger . error ( error ) ;
88- }
89- }
90-
91- public async destructor ( ) {
92- await this . closeConnection ( ) ;
93- }
94-
95- public async destroy ( ) {
96- await this . destructor ( ) ;
97- }
9897}
0 commit comments