All files / node-coap/lib cache.js

100% Statements 38/38
100% Branches 6/6
100% Functions 8/8
100% Lines 38/38

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 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84                1x     7x 7x                       629x 629x 629x 629x     1x 419x 20x 20x 20x               1x 424x 394x 394x 394x   30x 30x     424x     1x 239x 1x 1x 1x 1x   238x     1x 408x     1x 395x     1x 2x 1x   1x 1x 1x       1x
/*
 * Copyright (c) 2013-2021 node-coap contributors.
 *
 * node-coap is licensed under an MIT +no-false-attribs license.
 * All rights not explicitly granted in the MIT license are reserved.
 * See the included LICENSE file for more details.
 */
 
var debug = require('debug')('Block Cache')
 
function expiry (cache, k) {
  debug('delete expired cache entry, key:', k)
  delete cache[k]
}
 
/**
 * @class
 * @constructor
 * @template T
 * @param {number} retentionPeriod 
 * @param {()=>T} factory Function which returns new cache objects
 */
function BlockCache (retentionPeriod, factory) {
  /** @type {{[k:string]:{payload:T,timeoutId:NodeJS.Timeout}}} */
  this._cache = {}
  this._retentionPeriod = retentionPeriod
  debug("Created cache with " + (this._retentionPeriod/1000) + "s retention period")
  this._factory = factory
}
 
BlockCache.prototype.reset = function () {
  for (var k in this._cache) {
    debug('clean-up cache expiry timer, key:', k)
    clearTimeout(this._cache[k].timeoutId)
    delete this._cache[k]
  }
}
 
/** 
 * @param {string} key
 * @param {T} payload
 */
BlockCache.prototype.add = function (key, payload) {
  if (this._cache.hasOwnProperty(key)) {
    debug('reuse old cache entry, key:', key)
    clearTimeout(this._cache[key].timeoutId)
    this._cache[key].payload = payload
  } else {
    debug('add payload to cache, key:', key)
    this._cache[key] = {payload: payload}
  }
  // setup new expiry timer
  this._cache[key].timeoutId = setTimeout(expiry, this._retentionPeriod, this._cache, key)
}
 
BlockCache.prototype.remove = function (key) {
  if (this._cache.hasOwnProperty(key)) {
    debug('remove cache entry, key:', key)
    clearTimeout(this._cache[key].timeoutId)
    delete this._cache[key]
    return true
  }
  return false
}
 
BlockCache.prototype.contains = function (key) {
  return this._cache.hasOwnProperty(key)
}
 
BlockCache.prototype.get = function (key) {
  return this._cache[key].payload
}
 
BlockCache.prototype.getWithDefaultInsert = function (key) {
  if(this.contains(key)) {
    return this._cache[key].payload
  } else {
    let def = this._factory()
    this.add(key, def)
    return def
  }
}
 
module.exports = BlockCache