@@ -11,28 +11,41 @@ export interface ICacheService {
1111export class CacheService implements ICacheService {
1212 readonly #env: Environment
1313 readonly #cacheType: string
14- readonly #client: RedisClientType | KVNamespace
14+ #client: RedisClientType | KVNamespace
1515
1616 // biome-ignore lint/correctness/noUndeclaredVariables: <explanation>
1717 constructor ( env : Env ) {
1818 this . #env = env
1919 if ( this . #env. EFP_DATA_CACHE === undefined ) {
2020 this . #cacheType = 'redis'
21- this . #client = createClient ( {
22- url : this . #env. REDIS_URL
23- } )
24- this . #client. on ( 'error' , ( err : Error ) => {
25- console . log ( `Error: ${ err } ` )
26- } )
27- this . #client. connect ( )
21+ this . #client = this . createRedisClient ( )
2822 } else {
2923 this . #cacheType = 'kv'
3024 this . #client = this . #env. EFP_DATA_CACHE as KVNamespace
3125 }
3226 }
3327
28+ createRedisClient ( ) : RedisClientType {
29+ const client : RedisClientType = createClient ( {
30+ url : this . #env. REDIS_URL
31+ } )
32+ client . on ( 'error' , ( err : Error ) => {
33+ console . log ( `Error: ${ err } ` )
34+ client . quit ( )
35+ } )
36+ client . connect ( )
37+ return client
38+ }
39+
40+ closeClient ( ) : void {
41+ ; ( this . #client as RedisClientType ) . quit ( )
42+ }
43+
3444 async get ( key : string ) : Promise < { } | null > {
3545 if ( this . #cacheType === 'redis' ) {
46+ if ( ! this . #client) {
47+ this . #client = this . createRedisClient ( )
48+ }
3649 const result = await ( this . #client as RedisClientType ) . get ( key )
3750 return JSON . parse ( result as string ) as any
3851 }
@@ -41,6 +54,9 @@ export class CacheService implements ICacheService {
4154
4255 async put ( key : string , value : string ) : Promise < void > {
4356 if ( this . #cacheType === 'redis' ) {
57+ if ( ! this . #client) {
58+ this . #client = this . createRedisClient ( )
59+ }
4460 await ( this . #client as RedisClientType ) . set ( key , value , {
4561 EX : this . #env. CACHE_TTL
4662 } as any )
0 commit comments