-
Notifications
You must be signed in to change notification settings - Fork 56
/
ObjectSchema.js
269 lines (244 loc) · 9.25 KB
/
ObjectSchema.js
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
'use strict'
const { BaseSchema } = require('./BaseSchema')
const {
omit,
setAttribute,
isFluentSchema,
hasCombiningKeywords,
patchIdsWithParentId,
appendRequired,
} = require('./utils')
const initialState = {
type: 'object',
definitions: [],
properties: [],
required: [],
}
/**
* Represents a ObjectSchema.
* @param {Object} [options] - Options
* @param {StringSchema} [options.schema] - Default schema
* @param {boolean} [options.generateIds = false] - generate the id automatically e.g. #properties.foo
* @returns {StringSchema}
*/
const ObjectSchema = ({ schema = initialState, ...options } = {}) => {
// TODO LS think about default values and how pass all of them through the functions
options = {
generateIds: false,
factory: ObjectSchema,
...options,
}
return {
...BaseSchema({ ...options, schema }),
/**
* This keyword determines how child instances validate for objects, and does not directly validate the immediate instance itself.
* Validation with "additionalProperties" applies only to the child values of instance names that do not match any names in "properties",
* and do not match any regular expression in "patternProperties".
* For all such properties, validation succeeds if the child instance validates against the "additionalProperties" schema.
* Omitting this keyword has the same behavior as an empty schema.
*
* @param {FluentSchema|boolean} value
* {@link reference|https://json-schema.org/latest/json-schema-validation.html#rfc.section.6.5.6}
* @returns {FluentSchema}
*/
additionalProperties: value => {
if (typeof value !== 'boolean' && !isFluentSchema(value))
throw new Error("'additionalProperties' must be a boolean or a S")
if (value === false) {
return setAttribute({ schema, ...options }, [
'additionalProperties',
false,
'object',
])
}
const { $schema, ...rest } = value.valueOf()
return setAttribute({ schema, ...options }, [
'additionalProperties',
{ ...rest },
'array',
])
},
/**
* An object instance is valid against "maxProperties" if its number of properties is less than, or equal to, the value of this keyword.
*
* @param {number} max
* {@link reference|https://json-schema.org/latest/json-schema-validation.html#rfc.section.6.5.1}
* @returns {FluentSchema}
*/
maxProperties: max => {
if (!Number.isInteger(max))
throw new Error("'maxProperties' must be a Integer")
return setAttribute({ schema, ...options }, [
'maxProperties',
max,
'object',
])
},
/**
* An object instance is valid against "minProperties" if its number of properties is greater than, or equal to, the value of this keyword.
*
* @param {number} min
* {@link reference|https://json-schema.org/latest/json-schema-validation.html#rfc.section.6.5.2}
* @returns {FluentSchema}
*/
minProperties: min => {
if (!Number.isInteger(min))
throw new Error("'minProperties' must be a Integer")
return setAttribute({ schema, ...options }, [
'minProperties',
min,
'object',
])
},
/**
* Each property name of this object SHOULD be a valid regular expression, according to the ECMA 262 regular expression dialect.
* Each property value of this object MUST be a valid JSON Schema.
* This keyword determines how child instances validate for objects, and does not directly validate the immediate instance itself.
* Validation of the primitive instance type against this keyword always succeeds.
* Validation succeeds if, for each instance name that matches any regular expressions that appear as a property name in this keyword's value, the child instance for that name successfully validates against each schema that corresponds to a matching regular expression.
*
* @param {object} opts
* {@link reference|https://json-schema.org/latest/json-schema-validation.html#rfc.section.6.5.5}
* @returns {FluentSchema}
*/
patternProperties: opts => {
const values = Object.entries(opts).reduce((memo, [pattern, schema]) => {
if (!isFluentSchema(schema))
throw new Error(
"'patternProperties' invalid options. Provide a valid map e.g. { '^fo.*$': S.string() }"
)
return {
...memo,
[pattern]: omit(schema.valueOf(), ['$schema']),
}
}, {})
return setAttribute({ schema, ...options }, [
'patternProperties',
values,
'object',
])
},
/**
* This keyword specifies rules that are evaluated if the instance is an object and contains a certain property.
* This keyword's value MUST be an object. Each property specifies a dependency. Each dependency value MUST be an array or a valid JSON Schema.
* If the dependency value is a subschema, and the dependency key is a property in the instance, the entire instance must validate against the dependency value.
* If the dependency value is an array, each element in the array, if any, MUST be a string, and MUST be unique. If the dependency key is a property in the instance, each of the items in the dependency value must be a property that exists in the instance.
*
* @param {object} opts
* {@link reference|https://json-schema.org/latest/json-schema-validation.html#rfc.section.6.5.7}
* @returns {FluentSchema}
*/
dependencies: opts => {
const values = Object.entries(opts).reduce((memo, [prop, schema]) => {
if (!isFluentSchema(schema) && !Array.isArray(schema))
throw new Error(
"'dependencies' invalid options. Provide a valid map e.g. { 'foo': ['ba'] } or { 'foo': S.string() }"
)
return {
...memo,
[prop]: Array.isArray(schema)
? schema
: omit(schema.valueOf(), ['$schema', 'type', 'definitions']),
}
}, {})
return setAttribute({ schema, ...options }, [
'dependencies',
values,
'object',
])
},
/**
* If the instance is an object, this keyword validates if every property name in the instance validates against the provided schema.
* Note the property name that the schema is testing will always be a string.
*
* @param {FluentSchema} value
* {@link reference|https://json-schema.org/latest/json-schema-validation.html#rfc.section.6.5.7}
* @returns {FluentSchema}
*/
propertyNames: value => {
if (!isFluentSchema(value)) throw new Error("'propertyNames' must be a S")
return setAttribute({ schema, ...options }, [
'propertyNames',
omit(value.valueOf(), ['$schema']),
'object',
])
},
/**
* The value of "properties" MUST be an object. Each value of this object MUST be a valid JSON Schema
*
* {@link reference|https://json-schema.org/latest/json-schema-validation.html#rfc.section.6.5.4}
* @param {string} name
* @param {FluentSchema} props
* @returns {FluentSchema}
*/
prop: (name, props = {}) => {
const target = props.def ? 'definitions' : 'properties'
let attributes = props.valueOf()
const $id =
attributes.$id ||
(options.generateIds ? `#${target}/${name}` : undefined)
if (isFluentSchema(props)) {
attributes = patchIdsWithParentId({
schema: attributes,
parentId: $id,
...options,
})
const [schemaPatched, attributesPatched] = appendRequired({
schema,
attributes: {
...attributes,
name,
},
})
schema = schemaPatched
attributes = attributesPatched
}
const type = hasCombiningKeywords(attributes)
? undefined
: attributes.type
const $ref = attributes.$ref
// strip undefined values or empty arrays or internals
attributes = Object.entries({ ...attributes, $id, type }).reduce(
(memo, [key, value]) => {
return key === '$schema' ||
key === 'def' ||
value === undefined ||
(Array.isArray(value) && value.length === 0)
? memo
: { ...memo, [key]: value }
},
{}
)
return ObjectSchema({
schema: {
...schema,
[target]: [
...schema[target],
$ref ? { name, $ref } : Object.assign({}, { name }, attributes),
],
},
...options,
})
},
/**
* The "definitions" keywords provides a standardized location for schema authors to inline re-usable JSON Schemas into a more general schema.
* There are no restrictions placed on the values within the array.
*
* {@link reference|https://json-schema.org/latest/json-schema-validation.html#rfc.section.9}
* @param {string} name
* @param {FluentSchema} props
* @returns {FluentSchema}
*/
// FIXME LS move to BaseSchema and remove .prop
// TODO LS Is a definition a proper schema?
definition: (name, props = {}) =>
ObjectSchema({ schema, ...options }).prop(name, {
...props.valueOf(),
def: true,
}),
}
}
module.exports = {
ObjectSchema,
default: ObjectSchema,
}