Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[7.x] Extend @kbn/config-schema (#40118) #40341

Merged
merged 1 commit into from
Jul 4, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 8 additions & 2 deletions packages/kbn-config-schema/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ import {
MapOfOptions,
MapOfType,
MaybeType,
NeverType,
NumberOptions,
NumberType,
ObjectType,
Expand Down Expand Up @@ -72,7 +73,7 @@ function uri(options?: URIOptions): Type<string> {
return new URIType(options);
}

function literal<T extends string | number | boolean>(value: T): Type<T> {
function literal<T extends string | number | boolean | null>(value: T): Type<T> {
return new LiteralType(value);
}

Expand All @@ -88,6 +89,10 @@ function duration(options?: DurationOptions): Type<Duration> {
return new DurationType(options);
}

function never(): Type<never> {
return new NeverType();
}

/**
* Create an optional type
*/
Expand Down Expand Up @@ -167,7 +172,7 @@ function siblingRef<T>(key: string): SiblingReference<T> {

function conditional<A extends ConditionalTypeValue, B, C>(
leftOperand: Reference<A>,
rightOperand: Reference<A> | A,
rightOperand: Reference<A> | A | Type<unknown>,
equalType: Type<B>,
notEqualType: Type<C>,
options?: TypeOptions<B | C>
Expand All @@ -186,6 +191,7 @@ export const schema = {
literal,
mapOf,
maybe,
never,
number,
object,
oneOf,
Expand Down
61 changes: 61 additions & 0 deletions packages/kbn-config-schema/src/references/reference.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/

import { Reference } from './reference';
import { schema } from '../';

describe('Reference.isReference', () => {
it('handles primitives', () => {
expect(Reference.isReference(undefined)).toBe(false);
expect(Reference.isReference(null)).toBe(false);
expect(Reference.isReference(true)).toBe(false);
expect(Reference.isReference(1)).toBe(false);
expect(Reference.isReference('a')).toBe(false);
expect(Reference.isReference({})).toBe(false);
});

it('handles schemas', () => {
expect(
Reference.isReference(
schema.string({
defaultValue: 'value',
})
)
).toBe(false);

expect(
Reference.isReference(
schema.conditional(
schema.contextRef('context_value_1'),
schema.contextRef('context_value_2'),
schema.string(),
schema.string()
)
)
).toBe(false);
});

it('handles context references', () => {
expect(Reference.isReference(schema.contextRef('ref_1'))).toBe(true);
});

it('handles sibling references', () => {
expect(Reference.isReference(schema.siblingRef('ref_1'))).toBe(true);
});
});
2 changes: 1 addition & 1 deletion packages/kbn-config-schema/src/references/reference.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ import { internals, Reference as InternalReference } from '../internals';
export class Reference<T> {
public static isReference<V>(value: V | Reference<V> | undefined): value is Reference<V> {
return (
value !== undefined &&
value != null &&
typeof (value as Reference<V>).getSchema === 'function' &&
internals.isRef((value as Reference<V>).getSchema())
);
Expand Down

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

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

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

66 changes: 66 additions & 0 deletions packages/kbn-config-schema/src/types/conditional_type.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,72 @@ test('properly validates types according chosen schema', () => {
).toEqual('a');
});

test('properly validates when compares with Schema', () => {
const type = schema.conditional(
schema.contextRef('context_value_1'),
schema.number(),
schema.string({ minLength: 2 }),
schema.string({ minLength: 3 })
);

expect(() =>
type.validate('a', {
context_value_1: 0,
})
).toThrowErrorMatchingSnapshot();

expect(
type.validate('ab', {
context_value_1: 0,
})
).toEqual('ab');

expect(() =>
type.validate('ab', {
context_value_1: 'b',
})
).toThrowErrorMatchingSnapshot();

expect(
type.validate('abc', {
context_value_1: 'b',
})
).toEqual('abc');
});

test('properly validates when compares with "null" literal Schema', () => {
const type = schema.conditional(
schema.contextRef('context_value_1'),
schema.literal(null),
schema.string({ minLength: 2 }),
schema.string({ minLength: 3 })
);

expect(() =>
type.validate('a', {
context_value_1: null,
})
).toThrowErrorMatchingSnapshot();

expect(
type.validate('ab', {
context_value_1: null,
})
).toEqual('ab');

expect(() =>
type.validate('ab', {
context_value_1: 'b',
})
).toThrowErrorMatchingSnapshot();

expect(
type.validate('abc', {
context_value_1: 'b',
})
).toEqual('abc');
});

test('properly handles schemas with incompatible types', () => {
const type = schema.conditional(
schema.contextRef('context_value_1'),
Expand Down
9 changes: 6 additions & 3 deletions packages/kbn-config-schema/src/types/conditional_type.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,15 +27,18 @@ export type ConditionalTypeValue = string | number | boolean | object | null;
export class ConditionalType<A extends ConditionalTypeValue, B, C> extends Type<B | C> {
constructor(
leftOperand: Reference<A>,
rightOperand: Reference<A> | A,
rightOperand: Reference<A> | A | Type<unknown>,
equalType: Type<B>,
notEqualType: Type<C>,
options?: TypeOptions<B | C>
) {
const schema = internals.when(leftOperand.getSchema(), {
is: Reference.isReference(rightOperand) ? rightOperand.getSchema() : rightOperand,
otherwise: notEqualType.getSchema(),
is:
Reference.isReference(rightOperand) || rightOperand instanceof Type
? rightOperand.getSchema()
: rightOperand,
then: equalType.getSchema(),
otherwise: notEqualType.getSchema(),
});

super(schema, options);
Expand Down
1 change: 1 addition & 0 deletions packages/kbn-config-schema/src/types/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,3 +33,4 @@ export { RecordOfOptions, RecordOfType } from './record_type';
export { StringOptions, StringType } from './string_type';
export { UnionType } from './union_type';
export { URIOptions, URIType } from './uri_type';
export { NeverType } from './never_type';
6 changes: 6 additions & 0 deletions packages/kbn-config-schema/src/types/literal_type.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,10 @@ test('handles number', () => {
expect(literal(123).validate(123)).toBe(123);
});

test('handles null', () => {
expect(literal(null).validate(null)).toBe(null);
});

test('returns error when not correct', () => {
expect(() => literal('test').validate('foo')).toThrowErrorMatchingSnapshot();

Expand All @@ -41,6 +45,8 @@ test('returns error when not correct', () => {
expect(() => literal('test').validate([1, 2, 3])).toThrowErrorMatchingSnapshot();

expect(() => literal(123).validate('abc')).toThrowErrorMatchingSnapshot();

expect(() => literal(null).validate(42)).toThrowErrorMatchingSnapshot();
});

test('includes namespace in failure', () => {
Expand Down
75 changes: 75 additions & 0 deletions packages/kbn-config-schema/src/types/never_type.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/

import { schema } from '..';

test('throws on any value set', () => {
const type = schema.never();

expect(() => type.validate(1)).toThrowErrorMatchingSnapshot();
expect(() => type.validate('a')).toThrowErrorMatchingSnapshot();
expect(() => type.validate(null)).toThrowErrorMatchingSnapshot();
expect(() => type.validate({})).toThrowErrorMatchingSnapshot();
expect(() => type.validate(undefined)).not.toThrow();
});

test('throws on value set as object property', () => {
const type = schema.object({
name: schema.never(),
status: schema.string(),
});

expect(() =>
type.validate({ name: 'name', status: 'in progress' })
).toThrowErrorMatchingSnapshot();

expect(() => type.validate({ status: 'in progress' })).not.toThrow();
expect(() => type.validate({ name: undefined, status: 'in progress' })).not.toThrow();
});

test('works for conditional types', () => {
const type = schema.object({
name: schema.conditional(
schema.contextRef('context_value_1'),
schema.contextRef('context_value_2'),
schema.string(),
schema.never()
),
});

expect(
type.validate(
{ name: 'a' },
{
context_value_1: 0,
context_value_2: 0,
}
)
).toEqual({ name: 'a' });

expect(() =>
type.validate(
{ name: 'a' },
{
context_value_1: 0,
context_value_2: 1,
}
)
).toThrowErrorMatchingSnapshot();
});
34 changes: 34 additions & 0 deletions packages/kbn-config-schema/src/types/never_type.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/

import { internals } from '../internals';
import { Type } from './type';

export class NeverType extends Type<never> {
constructor() {
super(internals.any().forbidden());
}

protected handleError(type: string) {
switch (type) {
case 'any.unknown':
return "a value wasn't expected to be present";
}
}
}