All files / src/cache OverwriteAgedSetStrategy.ts

78.57% Statements 11/14
80% Branches 4/5
75% Functions 3/4
78.57% Lines 11/14

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    2x         2x         3x 1x     2x                                         2x 2x 2x 1x     1x     1x        
import { IAgingCacheSetStrategy } from './IAgingCacheWriteStrategy';
import { IAgingCacheWrite } from './IAgingCache';
import { AgingCacheWriteStrategy } from './AgingCacheWriteStrategy';
 
/**
 * Strategy to overwrite only if our value is newer than the high level
 */
export class OverwriteAgedSetStrategy<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>> {
    const currentAge = this.evictQueue.getInitialAge(key);
    return this.hierarchy.getValueAtTopLevel(key).then(highestAgedValue => {
      if (!highestAgedValue || this.evictQueue.compare(highestAgedValue.age, currentAge) <= 0) {
        return this.executeSet(key, value, evictAtLevel);
      }
 
      this.logger.debug(
        `Set deferred: key=${key},ageToSet=${currentAge},ageFound=${highestAgedValue.age}`
      );
      return this.setFromHighestLevel(key, highestAgedValue);
    });
  }
}