* Cache wrapper for functions (cache-aside). * * Bare JSON null is treated as a miss; use withCacheNullable for intentional null values. * Never throws due to cache errors; function errors propagate without retry. * * @param fn - Function to execute (and optionally cache). * @param
(
fn: () => Promise<T>,
key: CacheKey,
ttlMs: number
)
| 254 | * @returns Cached value if present, otherwise fresh result from fn() |
| 255 | */ |
| 256 | async withCache<T extends NonNullable<unknown>>( |
| 257 | fn: () => Promise<T>, |
| 258 | key: CacheKey, |
| 259 | ttlMs: number |
| 260 | ): Promise<T> { |
| 261 | if (!this.canUseCache(key, ttlMs)) { |
| 262 | return await fn(); |
| 263 | } |
| 264 | |
| 265 | const cachedValue = await this.tryGetCachedValue<T>(key, ttlMs); |
| 266 | if (cachedValue !== undefined) { |
| 267 | return cachedValue; |
| 268 | } |
| 269 | |
| 270 | const fresh = await fn(); |
| 271 | await this.trySetCache(key, fresh, ttlMs); |
| 272 | return fresh; |
| 273 | } |
| 274 | |
| 275 | /** |
| 276 | * Cache wrapper for functions whose result may legitimately be `null`. |
no test coverage detected