UNPKG

tadicl-p2

Version:

Servidor Node capaz de tratar peticiones REST y que implementa uso de cache con tiempo establecido

70 lines (57 loc) 2.15 kB
// Modulo cache.js cuya funcionalidad es guardar los pathname junto con los datos correspondientes del servicio RestFul // durante un tiempo especificado en cache. Luego se borra de la misma cuando expira el tiempo que le indicamos mediante variable.... var cache = {}; // almacenaremos los elementos... //getTimeNow en milisegundos... function getTimeNow() { return (new Date).getTime(); } //Insertar en cache exports.insertar = function(indice, valor, tiempo) { console.log('- Insertando elemento en cache: ' + indice + ' = ' + valor + ' ( ' + tiempo / 1000 + ' seg)'); //Mostramos elemento insertado en cache mediante consola... //Borramos el tiempo establecido del indice var viejoRegistro = cache[indice]; if (viejoRegistro) { clearTimeout(viejoRegistro.timeout); } //Tiempo de expiraci�n var expira = tiempo + getTimeNow(); //Registro formado por (indice+tiempo de expiracion) var registro = {value: indice, expire: expira}; //Seteamos timeout (cuando expira borra el indice) if (!isNaN(expira)) { var time_limite = setTimeout(function() { exports.borrar(indice);}, tiempo); registro.timeout = time_limite; } cache[indice] = registro; }; //Borrar elemento de cache exports.borrar = function(indice) { delete cache[indice]; }; //Limpiar cache exports.limpiar = function() { cache = {}; //vaciamos }; //Obtener elemento de cache exports.obtener = function(indice) { var dato = cache[indice]; if (typeof dato !== "undefined") { if (isNaN(dato.expira) || dato.expira >= getTimeNow()) { return dato.valor; //devolvemos el valor } else { exports.borrar(indice); //borramos indice } return null; } }; //Tama�o de cache... exports.size = function() { var size = 0, indice; //For para saber cuantos elementos tenemos en la cache... for (indice in cache) { if (cache.hasOwnProperty(indice)) if (exports.obtener(indice) !== null) size++; } return size; };