From 9b9344fc5c5b203e71754a7829c756ed6b1cd5c9 Mon Sep 17 00:00:00 2001 From: Bram Borggreve Date: Wed, 14 Dec 2022 19:43:48 +0000 Subject: [PATCH] feat: add support to cache 'raw' values without using () => Promise --- .../src/lib/api-cache-data-access.service.ts | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/libs/api/cache/data-access/src/lib/api-cache-data-access.service.ts b/libs/api/cache/data-access/src/lib/api-cache-data-access.service.ts index 89ce759f5..4cd7dd6ee 100644 --- a/libs/api/cache/data-access/src/lib/api-cache-data-access.service.ts +++ b/libs/api/cache/data-access/src/lib/api-cache-data-access.service.ts @@ -8,6 +8,9 @@ export function getCacheKey(namespace: CacheNamespace, key: string) { return `kinetic:${namespace}:${key}` } +export type Value = T | ValueFn +export type ValueFn = () => Promise + @Injectable() export class ApiCacheDataAccessService { private readonly logger = new Logger(ApiCacheDataAccessService.name) @@ -20,14 +23,19 @@ export class ApiCacheDataAccessService { /** * Get a value from the cache, or set it if it doesn't exist. */ - async wrap(namespace: CacheNamespace, key: string, fn: () => Promise, ttl?: number): Promise { + async wrap(namespace: CacheNamespace, key: string, value: Value, ttl?: number): Promise { + const fn: ValueFn = (typeof value === 'function' ? value : () => Promise.resolve(value)) as ValueFn const cacheKey = getCacheKey(namespace, key) const found = await this.get(namespace, key) if (!found) { const result = await fn() - await this.set(namespace, key, result, ttl) - this.logger.verbose(`${style.bYellow.apply('[CACHE MISS]')} ${cacheKey} ttl=${ttl} seconds`) - return result + if (result) { + await this.set(namespace, key, result, ttl) + this.logger.verbose(`${style.bYellow.apply('[CACHE MISS]')} ${cacheKey} ttl=${ttl} seconds`) + return result + } + this.logger.verbose(`${style.bYellow.apply('[CACHE PASS]')} ${cacheKey}, result is falsy`) + return } this.logger.verbose(`${style.bGreen.apply('[CACHE HIT]')} ${cacheKey} ttl=${ttl} seconds`)