/**
* @module flitter-orm/src/model/ResultCache
*/
const { Injectable } = require('flitter-di')
const hash = require('object-hash')
/**
* Cache for results of model lookups. Stores
* result sets by hash of the model name, and
* some lookup identifier.
* @extends module:flitter-di/src/Injectable~Injectable
*/
class ResultCache extends Injectable {
/**
* The cached result sets as model hash -> identifier -> result set.
* @type {object}
*/
#results = {}
/**
* Store a particular result set associated with the specified
* model and identifier.
* @param {module:flitter-orm/src/model/Model~Model} Model - static CLASS reference to the model
* @param {string} identifier - unique identifier for the result
* @param {*} result - the result to store
*/
store(Model, identifier, result) {
const model_hash = hash(Model)
if ( !this.#results[model_hash] ) this.#results[model_hash] = {}
this.#results[model_hash][identifier] = result
}
/**
* Returns true if the cache has an entry for the model/identifier combo.
* @param {module:flitter-orm/src/model/Model~Model} Model - static CLASS reference to the model
* @param {string} identifier - unique identifier for the result
* @returns {boolean}
*/
has(Model, identifier) {
const model_hash = hash(Model)
return !!(!!this.#results[model_hash] && !!this.#results[model_hash][identifier])
}
/**
* Get the result entry for the model/identifier combo.
* @param {module:flitter-orm/src/model/Model~Model} Model - static CLASS reference to the model
* @param {string} identifier - unique identifier for the result
* @returns {*} - the cached result
*/
get(Model, identifier) {
const model_hash = hash(Model)
return this.#results[model_hash][identifier]
}
}
module.exports = exports = ResultCache