Skip to content

Commit 8b63de5

Browse files
committedJun 28, 2024
add normalizer rule to transform type arrays to oneOf
1 parent 8ecf50b commit 8b63de5

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed
 

‎src/normalizer.ts

+37
Original file line numberDiff line numberDiff line change
@@ -286,6 +286,43 @@ rules.set('Add an $id to each named enum', schema => {
286286
schema.$id = toSafeString(justName(keyName))
287287
})
288288

289+
rules.set('Make implicit unions explicit', schema => {
290+
if (!Array.isArray(schema.type)) {
291+
return
292+
}
293+
294+
// TODO: Optimize this case too
295+
if (schema.oneOf) {
296+
return
297+
}
298+
299+
const oneOf = schema.type.map(t => {
300+
switch (t) {
301+
case 'object': {
302+
const s: AnnotatedJSONSchema = {
303+
[IsSchema]: true,
304+
[Parent]: schema,
305+
[Ref]: schema[Ref],
306+
}
307+
move(schema, s, 'patternProperties')
308+
move(schema, s, 'properties')
309+
move(schema, s, 'required')
310+
if (schema[Ref]) {
311+
delete schema[Ref]
312+
}
313+
return s
314+
}
315+
}
316+
})
317+
})
318+
319+
function move<A extends object>(from: A, to: A, key: keyof A): void {
320+
if (key in from) {
321+
to[key] = from[key]
322+
delete from[key]
323+
}
324+
}
325+
289326
export function normalize(rootSchema: AnnotatedJSONSchema, filename: string, options: Options): NormalizedJSONSchema {
290327
rules.forEach(rule => traverse(rootSchema, (schema, key) => rule(schema, filename, options, key)))
291328
return rootSchema as NormalizedJSONSchema

0 commit comments

Comments
 (0)
Failed to load comments.