/**
* Helper functions for managing `function` cache.
*
* @module Helper/Function
*/
/**
* Clear all cached function items.
*
* @async
* @method
* @param {object} [opts={}] - The options for clearing the cache
*/
export async function clear (opts = {}) {
this.fnCache = []
}
/**
* Get a cached function item by key.
*
* @async
* @method
* @param {object} [opts={}] - The options for retrieving the cached item
* @param {string} [opts.key] - The key of the cached function item
* @returns {Promise<*>} - Returns the cached function item or undefined if expired/not found
*/
export async function get (opts = {}) {
const { find } = this.app.lib._
const result = find(this.fnCache, { key: opts.key })
if (result && Date.now() > result.exp) {
await remove.call(this, opts)
return undefined
}
return result ? result.value : undefined
}
/**
* Remove a cached function item by key.
*
* @async
* @method
* @param {object} [opts={}] - The options for removing the cached item
* @param {string} [opts.key] - The key of the cached function item
*/
export async function remove (opts = {}) {
const { findIndex, pullAt } = this.app.lib._
const idx = findIndex(this.fnCache, { key: opts.key })
if (idx > -1) pullAt(this.fnCache, idx)
}
/**
* Set a cached function item.
*
* @async
* @method
* @param {object} [opts={}] - The options for setting the cached item
* @param {string} [opts.key] - The key of the cached function item
* @param {*} [opts.value] - The value of the cached function item
* @param {number} [opts.ttl] - The time-to-live for the cached function item
* @returns {Promise<boolean>} - Returns true if the item was successfully cached
*/
export async function set (opts = {}) {
const { merge } = this.app.lib._
opts.ttl = opts.ttl ?? this.config.default.ttlDur
const item = merge({}, opts, { exp: Date.now() + opts.ttl })
this.fnCache.push(item)
return true
}