Skip to content

Commit

Permalink
feat: add support to cache 'raw' values without using () => Promise
Browse files Browse the repository at this point in the history
  • Loading branch information
beeman committed Dec 14, 2022
1 parent 75ebd85 commit 9b9344f
Showing 1 changed file with 12 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@ export function getCacheKey(namespace: CacheNamespace, key: string) {
return `kinetic:${namespace}:${key}`
}

export type Value<T> = T | ValueFn<T>
export type ValueFn<T> = () => Promise<T>

@Injectable()
export class ApiCacheDataAccessService {
private readonly logger = new Logger(ApiCacheDataAccessService.name)
Expand All @@ -20,14 +23,19 @@ export class ApiCacheDataAccessService {
/**
* Get a value from the cache, or set it if it doesn't exist.
*/
async wrap<T>(namespace: CacheNamespace, key: string, fn: () => Promise<T>, ttl?: number): Promise<T> {
async wrap<T>(namespace: CacheNamespace, key: string, value: Value<T>, ttl?: number): Promise<T> {
const fn: ValueFn<T> = (typeof value === 'function' ? value : () => Promise.resolve(value)) as ValueFn<T>
const cacheKey = getCacheKey(namespace, key)
const found = await this.get<T>(namespace, key)
if (!found) {
const result = await fn()
await this.set<T>(namespace, key, result, ttl)
this.logger.verbose(`${style.bYellow.apply('[CACHE MISS]')} ${cacheKey} ttl=${ttl} seconds`)
return result
if (result) {
await this.set<T>(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`)
Expand Down

0 comments on commit 9b9344f

Please sign in to comment.