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