Skip to content

Commit

Permalink
Update Boolean to coerce strings to boolean values
Browse files Browse the repository at this point in the history
  • Loading branch information
jportner committed Jan 7, 2020
1 parent 0e8cea9 commit ff2da17
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 1 deletion.
18 changes: 17 additions & 1 deletion packages/kbn-config-schema/src/internals/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,23 @@ export const internals = Joi.extend([
base: Joi.boolean(),
coerce(value: any, state: State, options: ValidationOptions) {
// If value isn't defined, let Joi handle default value if it's defined.
if (value !== undefined && typeof value !== 'boolean') {
if (value === undefined) {
return value;
}

// Allow strings 'true' and 'false' to be coerced to booleans (case-insensitive).

// From Joi docs on `Joi.boolean`:
// > Generates a schema object that matches a boolean data type. Can also
// > be called via bool(). If the validation convert option is on
// > (enabled by default), a string (either "true" or "false") will be
// converted to a boolean if specified.
if (typeof value === 'string') {
const normalized = value.toLowerCase();
value = normalized === 'true' ? true : normalized === 'false' ? false : value;
}

if (typeof value !== 'boolean') {
return this.createError('boolean.base', { value }, state, options);
}

Expand Down

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

11 changes: 11 additions & 0 deletions packages/kbn-config-schema/src/types/boolean_type.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,13 @@ test('returns value by default', () => {
expect(schema.boolean().validate(true)).toBe(true);
});

test('handles boolean strings', () => {
expect(schema.boolean().validate('true')).toBe(true);
expect(schema.boolean().validate('TRUE')).toBe(true);
expect(schema.boolean().validate('false')).toBe(false);
expect(schema.boolean().validate('FALSE')).toBe(false);
});

test('is required by default', () => {
expect(() => schema.boolean().validate(undefined)).toThrowErrorMatchingSnapshot();
});
Expand All @@ -49,4 +56,8 @@ test('returns error when not boolean', () => {
expect(() => schema.boolean().validate([1, 2, 3])).toThrowErrorMatchingSnapshot();

expect(() => schema.boolean().validate('abc')).toThrowErrorMatchingSnapshot();

expect(() => schema.boolean().validate(0)).toThrowErrorMatchingSnapshot();

expect(() => schema.boolean().validate('no')).toThrowErrorMatchingSnapshot();
});

0 comments on commit ff2da17

Please sign in to comment.