1
0
mirror of https://github.com/node-red/node-red.git synced 2023-10-10 13:36:53 +02:00

update for merging settings object & better error handling

This commit is contained in:
Hiroyasu Nishiyama 2020-03-07 19:19:48 +09:00
parent c0d007ffa9
commit 82539fc420

View File

@ -60,27 +60,31 @@ nopt.invalidHandler = function(k,v,t) {
var parsedArgs = nopt(knownOpts,shortHands,process.argv,2) var parsedArgs = nopt(knownOpts,shortHands,process.argv,2)
/** /**
* Set property of specified object. * Marge values in second object into first object.
* @param {Object} obj - target object *
* @param {string} path - "." separated property path * @param {Object} obj0 - target object
* @param {Object} val - value to be set * @param {Object} obj1 - object to be merged
*/ */
function setProperty(obj, path, val) { function mergeObject(obj0, obj1) {
var paths = path.split("."); function isObject(o) {
if (paths.length > 0) { function typeOf(o) {
var o = obj; var toString = Object.prototype.toString;
for (var i = 0; i < paths.length -1; i++) { return toString.call(o).slice(8, -1);
var path = paths[i];
if (!o.hasOwnProperty(path)) {
o[path] = {};
}
o = o[path];
} }
var key = paths[paths.length-1]; return (typeOf(o) == "Object");
o[key] = val;
} }
Object.entries(obj1).forEach(([key, val]) => {
if (obj0.hasOwnProperty(key) && isObject(obj0[key]) && isObject(val)) {
mergeObject(obj0[key], val);
}
else {
obj0[key] = val;
}
})
return obj0;
} }
if (parsedArgs.help) { if (parsedArgs.help) {
console.log("Node-RED v"+RED.version()); console.log("Node-RED v"+RED.version());
console.log("Usage: node-red [-v] [-?] [--settings settings.js] [--userDir DIR]"); console.log("Usage: node-red [-v] [-?] [--settings settings.js] [--userDir DIR]");
@ -163,21 +167,21 @@ if (parsedArgs.define) {
if (match) { if (match) {
if (!match[4]) { if (!match[4]) {
var val = JSON.parse(match[3]); var val = JSON.parse(match[3]);
setProperty(settings, match[2], val); RED.util.setObjectProperty(settings, match[2], val, true);
} }
else { else {
var obj = fs.readJsonSync(match[4]); var obj = fs.readJsonSync(match[4]);
Object.entries(obj).forEach(([key, val]) => { mergeObject(settings, obj);
settings[key] = val;
});
} }
} }
else { else {
throw new Error("Unexpected option: "+def); throw new Error("unexpected syntax");
} }
} }
catch (e) { catch (e) {
console.log("Error processing option: "+def);
console.log(e); console.log(e);
process.exit();
} }
}); });
} }