All files / src/cache RefreshAlwaysSetStrategy.ts

81.25% Statements 13/16
75% Branches 6/8
80% Functions 4/5
81.25% Lines 13/16

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61    2x         2x         4x 1x     3x                                         3x 3x 1x     2x 2x       1x     1x         1x          
import { IAgingCacheSetStrategy } from './IAgingCacheWriteStrategy';
import { IAgingCacheWrite } from './IAgingCache';
import { AgingCacheWriteStrategy } from './AgingCacheWriteStrategy';
 
/**
 * Strategy to overwrite only if we're forced to
 */
export class RefreshAlwaysSetStrategy<TKey, TValue>
  extends AgingCacheWriteStrategy<TKey, TValue>
  implements IAgingCacheSetStrategy<TKey, TValue>
{
  set(key: TKey, value: TValue, force: boolean): Promise<IAgingCacheWrite<TValue>> {
    if (force) {
      return this.executeSet(key, value);
    }
 
    return this.setConditionally(key, value);
  }
 
  load(
    key: TKey,
    value: TValue,
    evictAtLevel?: number,
    force?: boolean
  ): Promise<IAgingCacheWrite<TValue>> {
    Iif (force) {
      return this.executeSet(key, value, evictAtLevel);
    }
 
    return this.setConditionally(key, value, evictAtLevel);
  }
 
  private setConditionally(
    key: TKey,
    value: TValue,
    evictAtLevel?: number
  ): Promise<IAgingCacheWrite<TValue>> {
    return this.hierarchy.getValueAtTopLevel(key).then(highestAgedValue => {
      if (!highestAgedValue) {
        return this.executeSet(key, value, evictAtLevel);
      }
 
      return this.hierarchy.getValueAtBottomLevel(key).then(lowestAgedValue => {
        if (
          lowestAgedValue &&
          this.evictQueue.compare(lowestAgedValue.age, highestAgedValue.age) === 0
        ) {
          return this.executeSet(key, value, evictAtLevel);
        }
 
        this.logger.debug(
          `Delete deferred: key=${key},ageToSet=${
            lowestAgedValue ? lowestAgedValue.age : 'null'
          },ageFound=${highestAgedValue.age}`
        );
        return this.setFromHighestLevel(key, highestAgedValue);
      });
    });
  }
}