Skip to content

Commit

Permalink
added forceDB option
Browse files Browse the repository at this point in the history
  • Loading branch information
Shahar-Y committed Mar 23, 2022
1 parent 4ff1c63 commit 03a3a7c
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 3 deletions.
12 changes: 9 additions & 3 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ class TryCache {
* If it succeeds it will return the cached value, and update the cache in the background.
* @param key - the key to get.
* @param retrieveFunction - the function to call if the key is not found in cache. <() => func(...params)>.
* @param opts - the options to use: { expire: number, callbackFunction: Function }.
* @param opts - the options to use: { expire: number, callbackFunction: Function, forceDB: boolean }.
* @returns the requested cache value, or the result of the retrieveFunction
* if no cache value is found.
*/
Expand All @@ -81,10 +81,16 @@ class TryCache {
callbackFunction: opts?.callbackFunction
? opts.callbackFunction
: defaults.defaultCallbackFunction,
forceDB: opts?.forceDB ? opts.forceDB : false,
};
try {
const cachedValue = await this.safeGetFromCache(key);
// If no value found, retrieve from DB and set
let cachedValue;

if (!operationOpts.forceDB) {
cachedValue = await this.safeGetFromCache(key);
}

// If no value found or forceDB activated, retrieve from DB and update cache
if (!cachedValue) {
const result = await retrieveFunction();
await this.safeSetCache(key, result, operationOpts.expire);
Expand Down
2 changes: 2 additions & 0 deletions src/paramTypes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,10 @@ export type TCOptions = {
/**
* expire - the expiration time in seconds.
* callbackFunction - the function to call if the retrieveFunction throws an error after cache failed.
* forceDB - if true, will force the retrieveFunction to be called even if the key is found in cache. Defaults to false.
*/
export type OperationOptions = {
expire: number;
callbackFunction: Function;
forceDB: boolean;
};

0 comments on commit 03a3a7c

Please sign in to comment.