-
Notifications
You must be signed in to change notification settings - Fork 14
/
json-schema.ts
54 lines (46 loc) · 1.28 KB
/
json-schema.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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import * as t from '../src/index'
export interface StringSchema {
type: 'string'
enum?: Array<string>
}
export interface NumberSchema {
type: 'number'
}
export interface BooleanSchema {
type: 'boolean'
}
export interface ObjectSchema {
type: 'object'
properties: { [key: string]: JSONSchema }
required?: Array<string>
}
export type JSONSchema = StringSchema | NumberSchema | BooleanSchema | ObjectSchema
function getRequiredProperties(schema: ObjectSchema): { [key: string]: true } {
const required: { [key: string]: true } = {}
if (schema.required) {
schema.required.forEach(function(k) {
required[k] = true
})
}
return required
}
function toInterfaceCombinator(schema: ObjectSchema): t.InterfaceCombinator {
const required = getRequiredProperties(schema)
return t.interfaceCombinator(
Object.keys(schema.properties).map(key =>
t.property(key, to(schema.properties[key]), !required.hasOwnProperty(key))
)
)
}
export function to(schema: JSONSchema): t.TypeReference {
switch (schema.type) {
case 'string':
return schema.enum ? t.keyofCombinator(schema.enum) : t.stringType
case 'number':
return t.numberType
case 'boolean':
return t.booleanType
case 'object':
return toInterfaceCombinator(schema)
}
}