|
| 1 | +import { LRUCache } from 'lru-cache'; |
| 2 | + |
| 3 | +import { CacheEntry } from './CacheEntry.js'; |
| 4 | +import { LogicError } from '../Error/index.js'; |
| 5 | +import { ParsedResponse } from '../Type/Definition/Response/index.js'; |
| 6 | + |
| 7 | +class Cache<T> { |
| 8 | + protected cache: LRUCache<string, CacheEntry<T>>; |
| 9 | + |
| 10 | + public has(key: string): boolean { |
| 11 | + return this.cache.has(key); |
| 12 | + } |
| 13 | + |
| 14 | + public get(key: string): CacheEntry<T> | undefined { |
| 15 | + return this.cache.get(key); |
| 16 | + } |
| 17 | + |
| 18 | + public set(key: string, value: CacheEntry<T>): this { |
| 19 | + this.cache.set(key, value); |
| 20 | + return this; |
| 21 | + } |
| 22 | + |
| 23 | + /** |
| 24 | + * Sets a cache entry with the given data and optional ETag. |
| 25 | + * If no ETag is provided, reuses the previous one if available. |
| 26 | + * |
| 27 | + * Reusing a known ETag can improve API performance when the data |
| 28 | + * is unchanged but the new source lacks ETag metadata. |
| 29 | + */ |
| 30 | + public setFromDataEtag(key: string, data: T, etag?: string | undefined): this { |
| 31 | + const previousCacheEntry = this.cache.get(key); |
| 32 | + if (previousCacheEntry && etag === undefined) { |
| 33 | + etag = previousCacheEntry.etag; |
| 34 | + } |
| 35 | + const cacheEntry = { |
| 36 | + data: data, |
| 37 | + etag: etag, |
| 38 | + }; |
| 39 | + this.cache.set(key, cacheEntry); |
| 40 | + return this; |
| 41 | + } |
| 42 | + |
| 43 | + public setFromParsedResponse(key: string, parsedResponse: ParsedResponse<T>): this { |
| 44 | + const etag = parsedResponse.response.headers.get('ETag'); |
| 45 | + if (etag === null) { |
| 46 | + throw new LogicError('Expected parsedResponse to contain ETag header.'); |
| 47 | + } |
| 48 | + const cacheEntry = { |
| 49 | + data: parsedResponse.data, |
| 50 | + etag: etag, |
| 51 | + }; |
| 52 | + this.cache.set(key, cacheEntry); |
| 53 | + return this; |
| 54 | + } |
| 55 | + |
| 56 | + public refresh(_key: string): this { |
| 57 | + // todo implement refresh |
| 58 | + return this; |
| 59 | + } |
| 60 | +} |
| 61 | + |
| 62 | +export { Cache }; |
0 commit comments