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

Extend @kbn/config-schema #40118

Merged
merged 7 commits into from
Jul 4, 2019
Merged
Show file tree
Hide file tree
Changes from 3 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
11 changes: 9 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,8 @@ import {
MapOfOptions,
MapOfType,
MaybeType,
NeverOptions,
NeverType,
NumberOptions,
NumberType,
ObjectType,
Expand Down Expand Up @@ -72,7 +74,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 +90,10 @@ function duration(options?: DurationOptions): Type<Duration> {
return new DurationType(options);
}

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

/**
* Create an optional type
*/
Expand Down Expand Up @@ -167,7 +173,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 +192,7 @@ export const schema = {
literal,
mapOf,
maybe,
never,
number,
object,
oneOf,
Expand Down
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 &&
mshustov marked this conversation as resolved.
Show resolved Hide resolved
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 { NeverOptions, 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
81 changes: 81 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,81 @@
/*
* 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();
});

test('allows customizing error message', () => {
const type = schema.never({ message: 'a rule was deprecated and removed, use [a] instead' });

expect(() => type.validate(1)).toThrowErrorMatchingSnapshot();
});
41 changes: 41 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,41 @@
/*
* 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, TypeOptions } from './type';

export type NeverOptions = TypeOptions<never> & {
message?: string;
mshustov marked this conversation as resolved.
Show resolved Hide resolved
};

export class NeverType extends Type<never> {
private readonly message?: string;
constructor(options: NeverOptions = {}) {
const { message, ...typeOptions } = options;
super(internals.any().forbidden(), typeOptions);
this.message = message;
}

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