_comuns/dist-back/cacheMemoria.js

33 lines
1.2 KiB
JavaScript

"use strict";
/** gerar uma função de cache para uso em memoria */
Object.defineProperty(exports, "__esModule", { value: true });
exports.cacheMFixo = exports.cacheMemoria = exports.verCacheM = exports.cacheM = void 0;
const _cache = {};
globalThis.cacheMemoria_cache = _cache;
const cacheM = (chave, valor, validadeSeg) => {
// converte a chave e string
const txChave = typeof chave == "string"
? chave
: typeof chave == "number"
? String(chave)
: encodeURIComponent(JSON.stringify(chave));
const validade = validadeSeg && new Date().getTime() + validadeSeg * 1000;
if (valor !== undefined) {
_cache[txChave] = {
valor,
validade,
};
}
const busca = _cache[txChave];
if (busca?.validade && busca.validade < new Date().getTime()) {
return undefined;
}
return busca?.valor;
};
exports.cacheM = cacheM;
const verCacheM = () => _cache;
exports.verCacheM = verCacheM;
exports.cacheMemoria = exports.cacheM;
/** para uso fixo dentro de uma função, trava a chave */
const cacheMFixo = (chave) => (valor) => (0, exports.cacheM)(chave, valor);
exports.cacheMFixo = cacheMFixo;