-
Notifications
You must be signed in to change notification settings - Fork 18
/
createSchemaOf.ts
32 lines (27 loc) · 887 Bytes
/
createSchemaOf.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import getTypeOf from "./getTypeOf";
import { JsonSchema } from "./types";
import { isObject } from "./utils/isObject";
/**
* Create a simple json schema for the given input data
* @param data - data to get json schema for
*/
export default function createSchemaOf(data: unknown): JsonSchema | undefined {
if (data === undefined) {
return undefined;
}
const schema: JsonSchema = {
type: getTypeOf(data)
};
if (schema.type === "object" && isObject(data)) {
schema.properties = {};
Object.keys(data).forEach((key) => (schema.properties[key] = createSchemaOf(data[key])));
}
if (schema.type === "array" && Array.isArray(data)) {
if (data.length === 1) {
schema.items = createSchemaOf(data[0]);
} else {
schema.items = data.map(createSchemaOf);
}
}
return schema;
}