'use strict'
module.exports = function (component) {
component.service('$cachePersonne', function ($cache, $settings) {
const ttl = $settings.get('components.personne.cacheTTL', 20 * 60)
/**
* Service de gestion du cache des personnes, helper de $personneRepository
* @service $cachePersonne
*/
const $cachePersonne = {}
/**
* Récupère une personne du cache d'après son id (oid ou pid)
* @param {string} id pid ou oid
* @param {personneCallback} next
* @memberOf $cachePersonne
*/
$cachePersonne.get = function (id, next) {
$cache.get('personne_' + id, next)
}
/**
* Met un objet personne en cache
* @param {Personne} personne
* @param {errorCallback} [next]
* @memberOf $cachePersonne
*/
$cachePersonne.set = function (personne, next = log.ifError) {
if (typeof personne.values !== 'function') return next(Error('$cachePersonne.set veut une Entity'))
const values = personne.values()
// by pid
$cache.set('personne_' + personne.pid, values, ttl, log.ifError)
// by oid
$cache.set('personne_' + personne.oid, values, ttl, next)
}
/**
* Efface un objet personne du cache
* @param {string} oid
* @param {errorCallback} [next]
* @memberOf $cachePersonne
*/
$cachePersonne.delete = function (oid, next = log.ifError) {
// faut faire un get pour récupérer le pid
$cachePersonne.get(oid, (error, personne) => {
if (error) return next(error)
if (!personne) return next()
$cache.delete('personne_' + personne.pid, log.ifError)
$cache.delete('personne_' + oid, next)
})
}
// on ajoute une possibilité noCache en conf, on écrase seulement les getters pour qu'ils ne renvoient rien
if ($settings.get('noCache', false)) {
log('$cacheRessource désactivé')
$cachePersonne.get = (oid, next) => next()
}
return $cachePersonne
})
}