|
| 1 | +import type { GenericCacheService } from '@/data/protocols/cache'; |
| 2 | +import type { Data, HttpClient, HttpResponse } from '@/data/protocols/http'; |
| 3 | +import { generateHashKeyToMemJs, logger } from '@/util'; |
| 4 | + |
| 5 | +type Services = 'memjs' | 'node-cache'; |
| 6 | + |
| 7 | +const DEFAULT_CACHE_SERVICE: Services = 'node-cache'; |
| 8 | +const DEFAULT_TTL_IN_MINUTES = 60; |
| 9 | + |
| 10 | +const MAX_RESULT_SIZE = 1024 * 1024 * 1; // ~ 1 MB |
| 11 | + |
| 12 | +export class CachedRequestAdapter implements HttpClient { |
| 13 | + constructor( |
| 14 | + private readonly httpClient: HttpClient, |
| 15 | + private readonly cacheService: GenericCacheService, |
| 16 | + private readonly options: { |
| 17 | + cacheService?: Services; |
| 18 | + headersFields?: string[]; |
| 19 | + ttl?: number; |
| 20 | + } = {} |
| 21 | + ) {} |
| 22 | + |
| 23 | + async request(data: Data): Promise<HttpResponse> { |
| 24 | + const key = this.generateCacheKey(data); |
| 25 | + const cachedResponse = await this.getCachedResponse(key); |
| 26 | + |
| 27 | + if (cachedResponse && Object.keys(cachedResponse).length > 1) |
| 28 | + return cachedResponse; |
| 29 | + |
| 30 | + const response = await this.httpClient.request(data); |
| 31 | + |
| 32 | + setImmediate(() => { |
| 33 | + this.saveToCache(key, response).catch((error) => { |
| 34 | + logger.log({ |
| 35 | + message: `Cache save error: ${error.message}`, |
| 36 | + level: 'warn' |
| 37 | + }); |
| 38 | + }); |
| 39 | + }); |
| 40 | + |
| 41 | + return response; |
| 42 | + } |
| 43 | + |
| 44 | + private generateCacheKey(data: Data): string { |
| 45 | + const method = data.method?.toUpperCase() || ''; |
| 46 | + const { url } = data; |
| 47 | + const headers = this.getRelevantHeaders(data.headers); |
| 48 | + const body = this.normalizeBody(data.body); |
| 49 | + |
| 50 | + const keyObject = { method, url, headers, body }; |
| 51 | + return generateHashKeyToMemJs(JSON.stringify(keyObject)); |
| 52 | + } |
| 53 | + |
| 54 | + private getRelevantHeaders( |
| 55 | + headers?: Record<string, unknown> |
| 56 | + ): Record<string, string> { |
| 57 | + if (!headers || !this.options.headersFields?.length) return {}; |
| 58 | + |
| 59 | + const relevantHeaders: Record<string, string> = {}; |
| 60 | + |
| 61 | + for (let i = 0; i < this.options.headersFields.length; i++) { |
| 62 | + const field = this.options.headersFields[i]; |
| 63 | + if (headers[field] !== undefined) { |
| 64 | + relevantHeaders[field] = String(headers[field]); |
| 65 | + } |
| 66 | + } |
| 67 | + |
| 68 | + return relevantHeaders; |
| 69 | + } |
| 70 | + |
| 71 | + private normalizeBody(body: unknown): unknown { |
| 72 | + if (typeof body !== 'object' || body === null || body === undefined) |
| 73 | + return body; |
| 74 | + return JSON.parse(JSON.stringify(body)); |
| 75 | + } |
| 76 | + |
| 77 | + private async getCachedResponse( |
| 78 | + key: string |
| 79 | + ): Promise<HttpResponse | undefined> { |
| 80 | + try { |
| 81 | + if (this.getCacheService() === 'node-cache') { |
| 82 | + return this.cacheService.get(key); |
| 83 | + } |
| 84 | + const buffer = await this.cacheService.get(key); |
| 85 | + return buffer ? JSON.parse(buffer.toString()) : undefined; |
| 86 | + } catch (error) { |
| 87 | + logger.log({ |
| 88 | + message: `Cache read error: ${error.message}`, |
| 89 | + level: 'warn' |
| 90 | + }); |
| 91 | + return undefined; |
| 92 | + } |
| 93 | + } |
| 94 | + |
| 95 | + private async saveToCache( |
| 96 | + key: string, |
| 97 | + response: HttpResponse |
| 98 | + ): Promise<void> { |
| 99 | + const responseString = JSON.stringify(response); |
| 100 | + |
| 101 | + if (Buffer.byteLength(responseString) > MAX_RESULT_SIZE) { |
| 102 | + return; |
| 103 | + } |
| 104 | + |
| 105 | + if (this.getCacheService() === 'node-cache') { |
| 106 | + this.cacheService.set(key, response, this.getTtl()); |
| 107 | + } else { |
| 108 | + await this.cacheService.set({ |
| 109 | + key, |
| 110 | + value: responseString, |
| 111 | + ttl: this.getTtl() |
| 112 | + }); |
| 113 | + } |
| 114 | + } |
| 115 | + |
| 116 | + private getCacheService(): Services { |
| 117 | + return this.options.cacheService || DEFAULT_CACHE_SERVICE; |
| 118 | + } |
| 119 | + |
| 120 | + private getTtl(): number { |
| 121 | + return this.options.ttl || DEFAULT_TTL_IN_MINUTES; |
| 122 | + } |
| 123 | +} |
0 commit comments