Skip to content

Commit a190bda

Browse files
committed
feat: add invalidateCache function to manage cache invalidation
1 parent 96c43ac commit a190bda

File tree

1 file changed

+26
-1
lines changed

1 file changed

+26
-1
lines changed

src/index.ts

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -166,6 +166,32 @@ export function cachedFunction<F extends CacheableFunction>(function_: F, option
166166
};
167167
}
168168

169+
/**
170+
* Invalidates the cache for a function based on the provided arguments.
171+
*
172+
* @template F - The type of the cacheable function.
173+
* @param function_ - The cacheable function.
174+
* @param arguments_ - The arguments of the cacheable function.
175+
* @param options - Optional configuration options for the cached function.
176+
* @returns {Promise<string>} - A promise that resolves to the cache key that was invalidated.
177+
* @throws {Error} - If no cache options are provided or cannot be inferred from the function.
178+
*/
179+
export async function invalidateCache<F extends CacheableFunction>(function_: F, arguments_: Parameters<F>, options?: CachedFunctionOptions<F>): Promise<string> {
180+
const cacheOptions = _.merge({}, options ?? {}, function_.cacheOptions ?? {});
181+
if (_.keys(cacheOptions).length === 0) {
182+
throw new Error('No cache options provided, either use the @CacheOptions decorator or provide options to cachedFunction directly.');
183+
}
184+
185+
const cacheKey = selectorToCacheKey(arguments_, cacheOptions.selector!, cacheOptions.namespace);
186+
const cache = await getOrInitializeCache(options as CachedFunctionInitializerOptions);
187+
188+
logger.trace({cacheKey}, 'Invalidating cache');
189+
await cache.del(cacheKey);
190+
logger.trace({cacheKey}, 'Cache invalidated');
191+
192+
return cacheKey;
193+
}
194+
169195
/**
170196
* Decorator for caching the result of a function based on selected arguments.
171197
*
@@ -179,7 +205,6 @@ export function cachedFunction<F extends CacheableFunction>(function_: F, option
179205
* @returns {Function} A decorator function that adds caching options to the method's descriptor.
180206
*/
181207
export function CacheOptions<F extends CacheableFunction>(selector: ArgumentPaths<F>, ttl?: number): any;
182-
183208
/**
184209
* Decorator for caching the result of a function.
185210
*

0 commit comments

Comments
 (0)