From 3d6dc88eb0c77d4bdeec93645d01d730c54e87d7 Mon Sep 17 00:00:00 2001 From: Cameron Diver Date: Mon, 11 Feb 2019 10:56:52 +0000 Subject: [PATCH] Make sure to correctly convert config emit events after validation We were validating the input configuration values by coercing them to the correct type, and then using the initial value to be saved (which currently is always converted to a string). We now use the coerced value as the actual value we will store, and more importantly emit. This means that the config.on('change' ...) calls will always be properly typed, which before this change was not a guarantee that we could make. Change-type: patch Signed-off-by: Cameron Diver --- src/config/index.ts | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/src/config/index.ts b/src/config/index.ts index e72b714a..54e62731 100644 --- a/src/config/index.ts +++ b/src/config/index.ts @@ -174,8 +174,8 @@ export class Config extends (EventEmitter as { }; return Bluebird.try(() => { - // Firstly validate all of the types as they are being set - this.validateConfigMap(keyValues); + // Firstly validate and coerce all of the types as they are being set + keyValues = this.validateConfigMap(keyValues); if (trx != null) { return setValuesInTransaction(trx).return(); @@ -251,10 +251,12 @@ export class Config extends (EventEmitter as { return schemaTypes[key].type.decode(value); } - private validateConfigMap(configMap: ConfigMap) { + private validateConfigMap( + configMap: ConfigMap, + ): ConfigMap { // Just loop over every value, run the decode function, and // throw if any value fails verification - _.map(configMap, (value, key) => { + return _.mapValues(configMap, (value, key) => { if ( !Schema.schema.hasOwnProperty(key) || !Schema.schema[key as Schema.SchemaKey].mutable @@ -276,13 +278,14 @@ export class Config extends (EventEmitter as { const decoded = type.decode(value); if (decoded.isLeft()) { - throw new Error( + throw new TypeError( `Cannot set value for ${key}, as value failed validation: ${ decoded.value }`, ); } - }); + return decoded.value; + }) as ConfigMap; } private generateRequiredFields() {