pbc/libs/cache.js

150 lines
2.9 KiB
JavaScript

const config = require('../config.json');
const logger = require('./logger.js');
const constants = require('./constants.js');
const active = config.cache.active;
const lifetime = config.cache.lifetime * 60000;
const cache = new Map();
function isActive() {
return active;
}
function getLifetime() {
return lifetime;
}
function clear() {
cache = new Map();
}
function validLifetime(timestamp) {
if (timestamp == undefined) {
return false;
}
if ((new Date().getTime() - timestamp) >= lifetime) {
return false;
}
return true;
}
function getValue(key) {
var value = cache.get(key);
if (value == undefined) {
return undefined;
}
if (!validLifetime(value.timestamp)) {
resetValue(key)
return undefined;
}
return cache.get(key).data;
}
function setValue(key, value) {
if (!active) {
return;
}
logger.debug('caching \'' + key + '\'...');
cache.set(key, { data: value, timestamp: new Date().getTime() });
}
function resetValue(key) {
cache.delete(key);
}
function getBanks() {
return getValue(constants.CACHE_BANKS);
}
function clearBanks() {
resetValue(constants.CACHE_BANKS);
}
function setBanks(value) {
setValue(constants.CACHE_BANKS, value);
}
function getPedalboards() {
return getValue(constants.CACHE_PEDALBOARDS);
}
function clearPedalboards() {
resetValue(constants.CACHE_PEDALBOARDS);
}
function setPedalboards(value) {
setValue(constants.CACHE_PEDALBOARDS, value);
}
function getCurrentPedalboard() {
return getValue(constants.CACHE_PEDALBOARD_CURRENT);
}
function clearCurrentPedalboard() {
resetValue(constants.CACHE_PEDALBOARD_CURRENT);
}
function setCurrentPedalboard(value) {
setValue(constants.CACHE_PEDALBOARD_CURRENT, value);
}
function getDefaultPedalboard() {
return getValue(constants.CACHE_PEDALBOARD_DEFAULT);
}
function clearDefaultPedalboard() {
resetValue(constants.CACHE_PEDALBOARD_DEFAULT);
}
function setDefaultPedalboard(value) {
setValue(constants.CACHE_PEDALBOARD_DEFAULT, value);
}
function getCurrentPedals() {
return getValue(constants.CACHE_PEDALS);
}
function clearCurrentPedals() {
resetValue(constants.CACHE_PEDALS);
}
function setCurrentPedals(value) {
setValue(constants.CACHE_PEDALS, value);
}
function getInfo() {
return getValue(constants.CACHE_INFO);
}
function clearInfo() {
resetValue(constants.CACHE_INFO);
}
function setInfo(value) {
setValue(constants.CACHE_INFO, value);
}
module.exports = {
isActive,
getLifetime,
clear,
getBanks,
clearBanks,
setBanks,
getPedalboards,
clearPedalboards,
setPedalboards,
getDefaultPedalboard,
clearDefaultPedalboard,
setDefaultPedalboard,
getCurrentPedalboard,
clearCurrentPedalboard,
setCurrentPedalboard,
getCurrentPedals,
clearCurrentPedals,
setCurrentPedals,
getInfo,
clearInfo,
setInfo
}