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

[feat] add reach-like functionality to object #37118

Merged
merged 5 commits into from
May 24, 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
12 changes: 12 additions & 0 deletions packages/kbn-config-schema/src/types/object_type.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -199,3 +199,15 @@ test('includes namespace in failure when wrong value type', () => {

expect(() => type.validate(value, {}, 'foo-namespace')).toThrowErrorMatchingSnapshot();
});

test('reach returns a valid schema component', () => {
toddself marked this conversation as resolved.
Show resolved Hide resolved
const type = schema.object({
foo: schema.boolean(),
});

const value = false;
expect(() => type.validateKey('foo', value)).toBeTruthy();
toddself marked this conversation as resolved.
Show resolved Hide resolved
expect(() => type.validateKey('bar', '')).toThrowErrorMatchingInlineSnapshot(
`"bar is not a valid part of this schema"`
);
});
10 changes: 10 additions & 0 deletions packages/kbn-config-schema/src/types/object_type.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@ export type TypeOf<RT extends Type<any>> = RT['type'];
export type ObjectResultType<P extends Props> = Readonly<{ [K in keyof P]: TypeOf<P[K]> }>;

export class ObjectType<P extends Props = any> extends Type<ObjectResultType<P>> {
private props: Record<string, AnySchema>;

constructor(props: P, options: TypeOptions<{ [K in keyof P]: TypeOf<P[K]> }> = {}) {
const schemaKeys = {} as Record<string, AnySchema>;
for (const [key, value] of Object.entries(props)) {
Expand All @@ -44,6 +46,7 @@ export class ObjectType<P extends Props = any> extends Type<ObjectResultType<P>>
.default();

super(schema, options);
this.props = schemaKeys;
}

protected handleError(type: string, { reason, value }: Record<string, any>) {
Expand All @@ -57,4 +60,11 @@ export class ObjectType<P extends Props = any> extends Type<ObjectResultType<P>>
return reason[0];
}
}

validateKey(key: string, value: any) {
if (!this.props[key]) {
throw new Error(`${key} is not a valid part of this schema`);
}
return this.props[key].validate(value);
}
}