Skip to content

Commit

Permalink
feat: support convert uniqueItems, minItems and maxItems keywords in …
Browse files Browse the repository at this point in the history
…json schema
  • Loading branch information
jakezhu9 committed Aug 9, 2023
1 parent 6b24b87 commit 0ed184c
Show file tree
Hide file tree
Showing 5 changed files with 59 additions and 0 deletions.
14 changes: 14 additions & 0 deletions pkg/tools/gen/genkcl_jsonschema.go
Original file line number Diff line number Diff line change
Expand Up @@ -233,6 +233,20 @@ func convertSchemaFromJsonSchema(ctx convertContext, s *jsonschema.Schema, name
result.Validations = append(result.Validations, validation{
MultiplyOf: &vInt,
})
case *jsonschema.UniqueItems:
if *v {
result.Validations = append(result.Validations, validation{
Unique: true,
})
}
case *jsonschema.MinItems:
result.Validations = append(result.Validations, validation{
MinLength: (*int)(v),
})
case *jsonschema.MaxItems:
result.Validations = append(result.Validations, validation{
MaxLength: (*int)(v),
})
default:
logger.GetLogger().Warningf("unknown Keyword: %s", k)
}
Expand Down
3 changes: 3 additions & 0 deletions pkg/tools/gen/templates/validator.gotmpl
Original file line number Diff line number Diff line change
Expand Up @@ -17,4 +17,7 @@
{{- if .MultiplyOf }}
multiplyof({{ formatName .Name }}, {{ .MultiplyOf }})
{{- end }}
{{- if .Unique }}
isunique({{ formatName .Name }})
{{- end }}
{{- end -}}
22 changes: 22 additions & 0 deletions pkg/tools/gen/testdata/jsonschema/items/expect.k
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
"""
This file was generated by the KCL auto-gen tool. DO NOT EDIT.
Editing this file might prove futile when you re-run the KCL auto-gen generate command.
"""

schema Book:
"""
Book

Attributes
----------
title : str, optional
authors : [str], optional
"""

title?: str
authors?: [str]

check:
len(authors) <= 5
len(authors) >= 1
isunique(authors)
19 changes: 19 additions & 0 deletions pkg/tools/gen/testdata/jsonschema/items/input.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"$id": "https://example.com/schemas/book.json",
"type": "object",
"properties": {
"title": {
"type": "string"
},
"authors": {
"type": "array",
"items": {
"type": "string"
},
"minItems": 1,
"maxItems": 5,
"uniqueItems": true
}
}
}
1 change: 1 addition & 0 deletions pkg/tools/gen/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,7 @@ type validation struct {
MaxLength *int
Regex *regexp.Regexp
MultiplyOf *int
Unique bool
}

// indexSignature is a kcl schema index signature definition.
Expand Down

0 comments on commit 0ed184c

Please sign in to comment.