-
Notifications
You must be signed in to change notification settings - Fork 199
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge compatible definitions in union types
Most validation keywords apply to only one of the basic types, so a "string" type and an "array" type can share a definition without colliding as a ["string", "array"] type, as long as they don't have any incompatibilities with each other. Modify UnionTypeFormatter to collapse these disjoint types into a single definition, without using anyOf.
- Loading branch information
Showing
2 changed files
with
38 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,25 @@ | ||
import { Definition } from "../Schema/Definition"; | ||
import { uniqueArray } from "./uniqueArray"; | ||
|
||
/** | ||
* Attempt to merge two disjoint definitions into one. Definitions are disjoint | ||
* (and therefore mergeable) if all of the following are true: | ||
* 1) Each has a 'type' property, and they share no types in common, | ||
* 2) The cross-type validation properties 'enum' and 'const' are not on either definition, and | ||
* 3) The two definitions have no properties besides 'type' in common. | ||
* | ||
* Returns the merged definition, or null if the two defs were not disjoint. | ||
*/ | ||
export function mergeDefinitions(def1: Definition, def2: Definition): Definition | null { | ||
const { type: type1, ...props1 } = def1; | ||
const { type: type2, ...props2 } = def2; | ||
const types = [type1!, type2!].flat(); | ||
if (!type1 || !type2 || uniqueArray(types).length !== types.length) { | ||
return null; | ||
} | ||
const keys = [Object.keys(props1), Object.keys(props2)].flat(); | ||
if (keys.includes("enum") || keys.includes("const") || uniqueArray(keys).length !== keys.length) { | ||
return null; | ||
} | ||
return { type: types, ...props1, ...props2 }; | ||
} |