Implement setProp in configs

Add setProp method for selectively changing one property of an object
field in a config group.
This commit is contained in:
Hornwitser committed 2020-05-31 16:08:21 +02:00
1 parent 8c9daff0bb
commit 5b043524b4
2 files changed
+106 -28

No files matched your search

+44 -1
View File
@@ -164,6 +164,14 @@ class Config extends events.EventEmitter {
return this.group(group).set(field, value);
}
/**
* Set property of an object value for a config field
*/
setProp(name, prop, value) {
let [group, field] = splitOn('.', name);
return this.group(group).setProp(field, prop, value);
}
/**
* Get the config group instance with the given name
*/
@@ -327,12 +335,13 @@ class ConfigGroup {
* The field must be defined for the config group and the value is
* type checked against the field definition.
*
* @throws {module:lib/config.InvalidField} if field is not defined.
* @throws {module:lib/config.InvalidValue} if value is not allowed for the field.
*/
set(name, value) {
let def = this.constructor._definitions.get(name);
if (!def) {
throw new Error(`No field named '${name}'`);
throw new InvalidField(`No field named '${name}'`);
}
// Empty strings are treates as null
@@ -382,6 +391,40 @@ class ConfigGroup {
}
}
/**
* Set property of object field
*
* Update value of stored object field by setting the specified property
* on it. The field must be defined as an object for the config group.
*
* @throws {module:lib/config.InvalidField} if field is not defined.
* @throws {module:lib/config.InvalidValue} if field is not an object.
*/
setProp(name, prop, value) {
let def = this.constructor._definitions.get(name);
if (!def) {
throw new InvalidField(`No field named '${name}'`);
}
if (def.type !== "object") {
throw new InvalidValue(`Cannot set property on non-object field '${name}'`);
}
let prev = this._fields.get(name);
let updated = {};
if (prev !== null) {
for (let [key, value] of Object.entries(prev)) {
updated[key] = value;
}
}
updated[prop] = value;
this._fields.set(name, updated);
if (this._config && !util.isDeepStrictEqual(updated, prev)) {
this._config.emit("fieldChanged", this, name, prev);
}
}
/**
* Update a config group from a serialized group
*