UNPKG

domotz-remote-pawn

Version:

Domotz Agent

112 lines (97 loc) 3.86 kB
/** * 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. */ const MODULE = 'CACHE'; var path = require('path'); module.exports.factory = function (procUtils, fs) { var env = process.env; var cacheDir = env.DOMOTZ_CACHE_DIR || path.join(env.DOMOTZ_ROOT_DIR, 'var', 'cache'); function getBaseDir(scope) { var baseDir = path.join(cacheDir, scope); return baseDir; } function getFileName(basePath, key) { return path.join(basePath, key + '.cache'); } function osAwarePath(pathname) { if (env.DPLATFORM === 'win') { return "'" + pathname + "'"; } return pathname; } function testCache(cache) { try { var stats = fs.lstatSync(cache); return stats.isFile(); } catch (error) { console.error('%s - error performing fs stat on %s', MODULE, cache); return false; } } function createCache(scope) { var basePath = getBaseDir(scope); console.info('%s - creating cache folder <%s>', MODULE, basePath); procUtils.exec('mkdir -p ' + osAwarePath(basePath)); return { test: function (key) { var cache = getFileName(basePath, key); return testCache(cache); }, get: function (key, missCallback, hitCallback) { var cache = getFileName(basePath, key); if (!testCache(cache)) { return missCallback(); } fs.readFile(cache, function (err, data) { if (err) { console.error('CACHE - Error reading file %s, cache miss', cache); missCallback(); } try { return hitCallback(JSON.parse(data)['cached-value']); } catch (error) { console.error('CACHE - Error parsing file %s contents, cache miss', cache); missCallback(); } }); }, set: function (key, value) { var cache = getFileName(basePath, key); var data = { 'cached-value': value }; var tempFile = cache + Math.random(); fs.writeFile(tempFile, JSON.stringify(data), function (err) { if (err) { console.error('%s - Cannot set cache value', MODULE); return console.error(err.stack); } procUtils.exec('mv ' + osAwarePath(tempFile) + ' ' + osAwarePath(cache)); console.info('%s - (%s): Key stored in cache in scope %s', MODULE, key, scope); }); }, reset: function () { procUtils.exec('rm -fr ' + osAwarePath(basePath)).catch(function () { console.error('%s - Error removing cache folder', MODULE); }); }, }; } return { createCache: createCache, }; };