domotz-remote-pawn
Version:
Domotz Agent
101 lines (87 loc) • 3.35 kB
JavaScript
/** This file is part of Domotz Agent.
* Copyright (C) 2016 Domotz Ltd
*
* Domotz Agent is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Domotz Agent is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Domotz Agent. If not, see <http://www.gnu.org/licenses/>.
**/
/**
*
* Created by Iacopo Papalini <ipapalini@domotz.com> on 17/09/15.
*/
module.exports.factory = function(procUtils, fs) {
function getBaseDir(scope) {
return process.env.DOMOTZ_ROOT_DIR + '/var/cache/' + scope + '/';
}
function fileName(basePath, key) {
return basePath + key + '.cache';
}
function testCache(cache) {
try {
var stats = fs.lstatSync(cache);
return stats.isFile();
}
catch (error) {
console.error("CACHE - error performing fs stat on " + cache);
return false;
}
}
function createCache(scope) {
var basePath = getBaseDir(scope);
procUtils.exec('mkdir -p ' + basePath);
return {
test: function (key) {
var cache = fileName(basePath, key);
return testCache(cache);
},
get: function (key, missCallback, hitCallback) {
var cache = fileName(basePath, key);
if (!testCache(cache)) {
return missCallback();
}
fs.readFile(cache, function (err, data) {
if (err) {
const fileName = cache;
console.error("CACHE - Error reading file %s, cache miss", fileName);
missCallback();
}
try {
return hitCallback(JSON.parse(data)['cached-value']);
}
catch (error) {
console.error("CACHE - Error parsing file %s contents, cache miss", fileName);
missCallback();
}
});
},
set: function (key, value) {
var cache = fileName(basePath, key);
var data = {'cached-value': value};
var tempFile = cache + Math.random();
fs.writeFile(tempFile, JSON.stringify(data), function (err) {
if (err) {
console.error("CACHE - Cannot set cache value");
return console.error(err.stack);
}
procUtils.exec('mv ' + tempFile + ' ' + cache);
console.info("CACHE - (%s): Key stored in cache in scope %s", key, scope);
});
},
reset: function () {
procUtils.exec('rm -fr ' + basePath);
}
};
}
return {
createCache: createCache
};
};