Skip to content

Commit

Permalink
feat: support union / array / tuple simplification
Browse files Browse the repository at this point in the history
  • Loading branch information
shigma committed Dec 7, 2022
1 parent bf439a5 commit 8ac18a7
Show file tree
Hide file tree
Showing 4 changed files with 19 additions and 10 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@
"typescript": "^4.9.3",
"vuepress": "2.0.0-beta.49",
"yakumo": "^0.3.7",
"yakumo-esbuild": "^0.3.18",
"yakumo-esbuild": "^0.3.19",
"yakumo-mocha": "^0.3.1",
"yakumo-publish": "^0.3.1",
"yakumo-tsc": "^0.3.6",
Expand Down
2 changes: 1 addition & 1 deletion packages/core/package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "schemastery",
"description": "Type driven schema validator",
"version": "3.6.0",
"version": "3.6.1",
"main": "lib/index.cjs",
"module": "lib/index.mjs",
"typings": "lib/index.d.ts",
Expand Down
23 changes: 16 additions & 7 deletions packages/core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -183,18 +183,20 @@ Schema.prototype.pattern = function pattern(regexp) {

Schema.prototype.simplify = function simplify(this: Schema, value) {
if (deepEqual(value, this.meta.default)) return
if (this.type === 'object') {
if (this.type === 'object' || this.type === 'dict') {
const result: Dict = {}
for (const key in value) {
const item = this.dict![key]?.simplify(value[key])
const schema = this.type === 'object' ? this.dict![key] : this.inner
const item = schema?.simplify(value[key])
if (!isNullable(item)) result[key] = item
}
return result
} else if (this.type === 'dict') {
const result: Dict = {}
for (const key in value) {
const item = this.inner?.simplify(value[key])
if (!isNullable(item)) result[key] = item
} else if (this.type === 'array' || this.type === 'tuple') {
const result: any[] = []
for (const key of value) {
const schema = this.type === 'array' ? this.inner : this.list![key]
const item = schema ? schema.simplify(value[key]) : value[key]
result.push(item)
}
return result
} else if (this.type === 'intersect') {
Expand All @@ -203,6 +205,13 @@ Schema.prototype.simplify = function simplify(this: Schema, value) {
Object.assign(result, item.simplify(value))
}
return result
} else if (this.type === 'union') {
for (const schema of this.list!) {
try {
Schema.resolve(value, schema)
return schema.simplify(value)
} catch {}
}
}
return value
}
Expand Down
2 changes: 1 addition & 1 deletion packages/form/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,6 @@
"vue": "^3"
},
"dependencies": {
"schemastery": "^3.6.0"
"schemastery": "^3.6.1"
}
}

0 comments on commit 8ac18a7

Please sign in to comment.