config: try to coerce string values into numbers

This commit is contained in:
Patrik Oldsberg
2020-09-03 16:35:16 +02:00
parent 3877a50ce9
commit 265be1d6a1
3 changed files with 18 additions and 24 deletions
+1 -1
View File
@@ -88,7 +88,7 @@ function expectInvalidValues(config: ConfigReader) {
"Invalid type in config for key 'string' in 'ctx', got string, wanted boolean",
);
expect(() => config.getNumber('string')).toThrow(
"Invalid type in config for key 'string' in 'ctx', got string, wanted number",
"Unable to convert config value for key 'string' in 'ctx' to a number",
);
expect(() => config.getString('one')).toThrow(
"Invalid type in config for key 'one' in 'ctx', got number, wanted string",
+17 -2
View File
@@ -49,6 +49,9 @@ const errors = {
missing(key: string) {
return `Missing required config value at '${key}'`;
},
convert(key: string, context: string, expected: string) {
return `Unable to convert config value for key '${key}' in '${context}' to a ${expected}`;
},
};
export class ConfigReader implements Config {
@@ -183,10 +186,22 @@ export class ConfigReader implements Config {
}
getOptionalNumber(key: string): number | undefined {
return this.readConfigValue(
const value = this.readConfigValue<string | number>(
key,
value => typeof value === 'number' || { expected: 'number' },
val =>
typeof val === 'number' ||
typeof val === 'string' || { expected: 'number' },
);
if (typeof value === 'number' || value === undefined) {
return value;
}
const number = Number(value);
if (!Number.isFinite(number)) {
throw new Error(
errors.convert(this.fullKey(key), this.context, 'number'),
);
}
return number;
}
getBoolean(key: string): boolean {