2015-07-20 03:49:48 +00:00
|
|
|
/* jslint node: true */
|
|
|
|
'use strict';
|
|
|
|
|
2018-06-14 03:02:00 +00:00
|
|
|
// deps
|
|
|
|
const paths = require('path');
|
|
|
|
const fs = require('graceful-fs');
|
|
|
|
const hjson = require('hjson');
|
|
|
|
const sane = require('sane');
|
|
|
|
|
|
|
|
module.exports = new class ConfigCache
|
|
|
|
{
|
2018-06-22 05:15:04 +00:00
|
|
|
constructor() {
|
|
|
|
this.cache = new Map(); // path->parsed config
|
|
|
|
}
|
2015-07-20 03:49:48 +00:00
|
|
|
|
2018-06-22 05:15:04 +00:00
|
|
|
getConfigWithOptions(options, cb) {
|
|
|
|
const cached = this.cache.has(options.filePath);
|
2018-06-14 03:02:00 +00:00
|
|
|
|
2018-06-22 05:15:04 +00:00
|
|
|
if(options.forceReCache || !cached) {
|
|
|
|
this.recacheConfigFromFile(options.filePath, (err, config) => {
|
|
|
|
if(!err && !cached) {
|
|
|
|
if(!options.noWatch) {
|
|
|
|
const watcher = sane(
|
|
|
|
paths.dirname(options.filePath),
|
|
|
|
{
|
|
|
|
glob : `**/${paths.basename(options.filePath)}`
|
|
|
|
}
|
|
|
|
);
|
2018-06-14 03:02:00 +00:00
|
|
|
|
2018-06-22 05:15:04 +00:00
|
|
|
watcher.on('change', (fileName, fileRoot) => {
|
|
|
|
require('./logger.js').log.info( { fileName, fileRoot }, 'Configuration file changed; re-caching');
|
2018-06-14 03:02:00 +00:00
|
|
|
|
2018-06-22 05:15:04 +00:00
|
|
|
this.recacheConfigFromFile(paths.join(fileRoot, fileName), err => {
|
|
|
|
if(!err) {
|
|
|
|
if(options.callback) {
|
|
|
|
options.callback( { fileName, fileRoot } );
|
|
|
|
}
|
|
|
|
}
|
|
|
|
});
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return cb(err, config, true);
|
|
|
|
});
|
|
|
|
} else {
|
|
|
|
return cb(null, this.cache.get(options.filePath), false);
|
|
|
|
}
|
|
|
|
}
|
2015-07-20 03:49:48 +00:00
|
|
|
|
2018-06-22 05:15:04 +00:00
|
|
|
getConfig(filePath, cb) {
|
|
|
|
return this.getConfigWithOptions( { filePath }, cb);
|
|
|
|
}
|
2015-07-20 03:49:48 +00:00
|
|
|
|
2018-06-22 05:15:04 +00:00
|
|
|
recacheConfigFromFile(path, cb) {
|
|
|
|
fs.readFile(path, { encoding : 'utf-8' }, (err, data) => {
|
|
|
|
if(err) {
|
|
|
|
return cb(err);
|
|
|
|
}
|
2015-07-20 03:49:48 +00:00
|
|
|
|
2018-06-22 05:15:04 +00:00
|
|
|
let parsed;
|
|
|
|
try {
|
|
|
|
parsed = hjson.parse(data);
|
|
|
|
this.cache.set(path, parsed);
|
|
|
|
} catch(e) {
|
|
|
|
require('./logger.js').log.error( { filePath : path, error : e.message }, 'Failed to re-cache' );
|
|
|
|
return cb(e);
|
|
|
|
}
|
2015-07-20 03:49:48 +00:00
|
|
|
|
2018-06-22 05:15:04 +00:00
|
|
|
return cb(null, parsed);
|
|
|
|
});
|
|
|
|
}
|
2015-07-24 04:23:44 +00:00
|
|
|
};
|