Allow simple type mismatches and coerce values accordingly.

Signed-off-by: Eric Peterson <ericpeterson@spotify.com>
This commit is contained in:
Eric Peterson
2023-03-23 10:59:28 +01:00
parent 1b3814cc73
commit c791fcd96b
5 changed files with 14 additions and 4 deletions
+7
View File
@@ -0,0 +1,7 @@
---
'@backstage/config-loader': minor
---
Configuration validation is now more permissive when it comes to config whose values are `string` but whose schemas declare them to be `boolean` or `number`.
For example, configuration was previously marked invalid when a string `'true'` was set on a property expecting type `boolean` or a string `'146'` was set on a property expecting type `number` (as when providing configuration via variable substitution sourced from environment variables). Now, such configurations will be considered valid and their values will be coerced to the right type at read-time.
@@ -28,7 +28,7 @@ describe('compileConfigSchemas', () => {
value: { type: 'object', properties: { b: { type: 'number' } } },
},
]);
expect(validate([{ data: { a: 1 }, context: 'test' }])).toEqual({
expect(validate([{ data: { a: [1] }, context: 'test' }])).toEqual({
errors: [
{
keyword: 'type',
@@ -45,6 +45,7 @@ export function compileConfigSchemas(
const ajv = new Ajv({
allErrors: true,
allowUnionTypes: true,
coerceTypes: true,
schemas: {
'https://backstage.io/schema/config-v1': true,
},
@@ -103,7 +103,7 @@ describe('loadConfigSchema', () => {
},
]);
expect(() =>
schema2.process([...configs, { data: { key1: 3 }, context: 'test2' }]),
schema2.process([...configs, { data: { key1: [3] }, context: 'test2' }]),
).toThrow(
'Config validation failed, Config must be string { type=string } at /key1',
);
@@ -202,11 +202,11 @@ describe('loadConfigSchema', () => {
context: 'test',
},
]);
expect(() => schema.process(mkConfig({ y: 1 }))).toThrow(
expect(() => schema.process(mkConfig({ y: [1] }))).toThrow(
'Config validation failed, Config must be string { type=string } at /nested/0/y',
);
expect(() =>
schema.process(mkConfig({ y: 1 }), { visibility: ['frontend'] }),
schema.process(mkConfig({ y: [1] }), { visibility: ['frontend'] }),
).toThrow(
'Config validation failed, Config must be string { type=string } at /nested/0/y',
);
+2
View File
@@ -59,6 +59,8 @@ function expectValidValues(config: ConfigReader) {
expect(config.has('nested.null')).toBe(true);
expect(config.getNumber('zero')).toBe(0);
expect(config.getNumber('one')).toBe(1);
expect(config.getNumber('zeroString')).toBe(0);
expect(config.getNumber('oneString')).toBe(1);
expect(config.getOptional('true')).toBe(true);
expect(config.getBoolean('true')).toBe(true);
expect(config.getBoolean('false')).toBe(false);