lib_generic.js

/**
 * Helper functions for managing `generic` cache.
 *
 * @module Helper/Generic
 */

/**
 * Clear cached items from the store.
 *
 * @async
 * @method
 * @param {object} [opts={}] - The options for clearing the cache
 * @param {string} [opts.key] - The key of the cached item to clear
 * @returns {Promise<void>}
 */
export async function clear (opts = {}) {
  if (!this.instance) return
  const { outmatch } = this.app.lib
  if (opts.key) {
    const isMatch = outmatch(opts.key + '*')
    // TODO: store needs to support iterator() method
    const { storage } = this.instance._store
    const items = await storage.findAllRecord(undefined, { noHook: true, noModelHook: true, noDynHook: true, dataOnly: true })
    for (const item of items) {
      const idx = item.id.indexOf(':')
      const key = item.id.substring(idx + 1)
      if (isMatch(key)) await this.instance.delete(key)
    }
    return
  }
  this.instance.clear()
}

/**
 * Get a cached item from the store.
 *
 * @async
 * @method
 * @param {object} [opts={}] - The options for retrieving the cached item
 * @param {string} [opts.key] - The key of the cached item
 * @returns {Promise<*>} - Returns the cached item or false if not found
 */
export async function get (opts = {}) {
  if (!this.instance) return
  if (!opts.key) return false
  const { isEmpty } = this.app.lib._
  const result = await this.instance.get(opts.key)
  return isEmpty(result) ? false : result
}

/**
 * Remove a cached item from the store.
 *
 * @async
 * @method
 * @param {object} [opts={}] - The options for removing the cached item
 * @param {string} [opts.key] - The key of the cached item to remove
 * @returns {Promise<void>}
 */
export async function remove (opts = {}) {
  if (!this.instance) return
  if (!opts.key) return
  await this.instance.delete(opts.key)
}

/**
 * Set a cached item in the store.
 *
 * @async
 * @method
 * @param {object} [opts={}] - The options for setting the cached item
 * @param {string} [opts.key] - The key of the cached item
 * @param {*} [opts.value] - The value of the cached item
 * @param {number} [opts.ttl] - The time-to-live for the cached item
 * @returns {Promise<void>}
 */
export async function set (opts = {}) {
  if (!this.instance) return
  if (!opts.key) return
  let ttl = opts.ttl ?? this.config.default.ttlDur
  if (ttl <= 0) ttl = 1
  await this.instance.set(opts.key, opts.value, ttl)
}