kibana/packages/kbn-io-ts-utils/src/to_json_schema/index.ts
Dario Gieselaar 821aeb1ff4
[APM] Typed client-side routing (#104274)
* [APM] @kbn/typed-router-config

* [APM] typed route config

* Breadcrumbs, wildcards

* Migrate settings, home

* Migrate part of service detail page

* Migrate remaining routes, tests

* Set maxWorkers for precommit script to 4

* Add jest types to tsconfigs

* Make sure transaction distribution data is fetched

* Fix typescript errors

* Remove usage of react-router's useParams

* Add route() utility function

* Don't use ApmServiceContext for alert flyouts

* Don't add onClick handler for breadcrumb

* Clarify ts-ignore

* Remove unused things

* Update documentation

* Use useServiceName() in ServiceMap component
2021-07-15 11:30:59 +02:00

87 lines
2 KiB
TypeScript

/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
import * as t from 'io-ts';
import { mapValues } from 'lodash';
import { isParsableType } from '../parseable_types';
interface JSONSchemaObject {
type: 'object';
required?: string[];
properties?: Record<string, JSONSchema>;
additionalProperties?: boolean | JSONSchema;
}
interface JSONSchemaOneOf {
oneOf: JSONSchema[];
}
interface JSONSchemaAllOf {
allOf: JSONSchema[];
}
interface JSONSchemaAnyOf {
anyOf: JSONSchema[];
}
interface JSONSchemaArray {
type: 'array';
items?: JSONSchema;
}
interface BaseJSONSchema {
type: string;
}
type JSONSchema =
| JSONSchemaObject
| JSONSchemaArray
| BaseJSONSchema
| JSONSchemaOneOf
| JSONSchemaAllOf
| JSONSchemaAnyOf;
export const toJsonSchema = (type: t.Mixed): JSONSchema => {
if (isParsableType(type)) {
switch (type._tag) {
case 'ArrayType':
return { type: 'array', items: toJsonSchema(type.type) };
case 'BooleanType':
return { type: 'boolean' };
case 'DictionaryType':
return { type: 'object', additionalProperties: toJsonSchema(type.codomain) };
case 'InterfaceType':
return {
type: 'object',
properties: mapValues(type.props, toJsonSchema),
required: Object.keys(type.props),
};
case 'PartialType':
return { type: 'object', properties: mapValues(type.props, toJsonSchema) };
case 'UnionType':
return { anyOf: type.types.map(toJsonSchema) };
case 'IntersectionType':
return { allOf: type.types.map(toJsonSchema) };
case 'NumberType':
return { type: 'number' };
case 'StringType':
return { type: 'string' };
}
}
return {
type: 'object',
};
};