oex2003/evolution-api
0
1import { ICache } from '@api/abstract/abstract.cache';2import { Logger } from '@config/logger.config';3import { BufferJSON } from 'baileys';4 5export class CacheService {6 private readonly logger = new Logger('CacheService');7 8 constructor(private readonly cache: ICache) {9 if (cache) {10 this.logger.verbose(`cacheservice created using cache engine: ${cache.constructor?.name}`);11 } else {12 this.logger.verbose(`cacheservice disabled`);13 }14 }15 16 async get(key: string): Promise<any> {17 if (!this.cache) {18 return;19 }20 return this.cache.get(key);21 }22 23 public async hGet(key: string, field: string) {24 if (!this.cache) {25 return null;26 }27 try {28 const data = await this.cache.hGet(key, field);29 30 if (data) {31 return JSON.parse(data, BufferJSON.reviver);32 }33 34 return null;35 } catch (error) {36 this.logger.error(error);37 return null;38 }39 }40 41 async set(key: string, value: any, ttl?: number) {42 if (!this.cache) {43 return;44 }45 this.cache.set(key, value, ttl);46 }47 48 public async hSet(key: string, field: string, value: any) {49 if (!this.cache) {50 return;51 }52 try {53 const json = JSON.stringify(value, BufferJSON.replacer);54 55 await this.cache.hSet(key, field, json);56 } catch (error) {57 this.logger.error(error);58 }59 }60 61 async has(key: string) {62 if (!this.cache) {63 return;64 }65 return this.cache.has(key);66 }67 68 async delete(key: string) {69 if (!this.cache) {70 return;71 }72 return this.cache.delete(key);73 }74 75 async hDelete(key: string, field: string) {76 if (!this.cache) {77 return false;78 }79 try {80 await this.cache.hDelete(key, field);81 return true;82 } catch (error) {83 this.logger.error(error);84 return false;85 }86 }87 88 async deleteAll(appendCriteria?: string) {89 if (!this.cache) {90 return;91 }92 return this.cache.deleteAll(appendCriteria);93 }94 95 async keys(appendCriteria?: string) {96 if (!this.cache) {97 return;98 }99 return this.cache.keys(appendCriteria);100 }101}102 