All files / src/cache OverwriteAgedDeleteStrategy.ts

81.25% Statements 13/16
87.5% Branches 7/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    2x         2x         5x 1x     4x                       4x 4x 1x     3x 3x       1x     2x         2x          
import { IAgingCacheDeleteStrategy } 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 OverwriteAgedDeleteStrategy<TKey, TValue>
  extends AgingCacheWriteStrategy<TKey, TValue>
  implements IAgingCacheDeleteStrategy<TKey, TValue>
{
  delete(key: TKey, force: boolean): Promise<IAgingCacheWrite<TValue>> {
    if (force) {
      return this.executeDelete(key);
    }
 
    return this.deleteConditionally(key);
  }
 
  evict(key: TKey, evictAtLevel?: number, force?: boolean): Promise<IAgingCacheWrite<TValue>> {
    Iif (force) {
      return this.executeDelete(key, evictAtLevel);
    }
 
    return this.deleteConditionally(key, evictAtLevel);
  }
 
  private deleteConditionally(key: TKey, evictAtLevel?: number): Promise<IAgingCacheWrite<TValue>> {
    return this.hierarchy.getValueAtTopLevel(key).then(highestAgedValue => {
      if (!highestAgedValue) {
        return this.executeDelete(key, evictAtLevel);
      }
 
      return this.hierarchy.getValueAtBottomLevel(key).then(lowestAgedValue => {
        if (
          lowestAgedValue &&
          this.evictQueue.compare(lowestAgedValue.age, highestAgedValue.age) >= 0
        ) {
          return this.executeDelete(key, evictAtLevel);
        }
 
        this.logger.debug(
          `Delete deferred: key=${key},ageToSet=${
            lowestAgedValue ? lowestAgedValue.age : 'null'
          },ageFound=${highestAgedValue.age}`
        );
        return this.setFromHighestLevel(key, highestAgedValue);
      });
    });
  }
}