Skip to content

Commit

Permalink
Allow arrays to use allowNull keyword (#26)
Browse files Browse the repository at this point in the history
  • Loading branch information
WC authored Jun 7, 2019
1 parent 91708fb commit 333ed5c
Show file tree
Hide file tree
Showing 5 changed files with 46 additions and 3 deletions.
28 changes: 28 additions & 0 deletions fixtures/arrays.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
{
"$ref": "#/definitions/testmodels.Arrays",
"$schema": "http://json-schema.org/draft-07/schema#",
"definitions": {
"testmodels.Arrays": {
"additionalProperties": false,
"properties": {
"pets": {
"items": {
"type": "integer"
},
"oneOf": [
{
"type": "array"
},
{
"type": "null"
}
]
}
},
"required": [
"pets"
],
"type": "object"
}
}
}
5 changes: 5 additions & 0 deletions internal/testmodels/arrays.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
package testmodels

type Arrays struct {
Pets []int `json:"pets" jsonschema:"allowNull"`
}
10 changes: 10 additions & 0 deletions reflect.go
Original file line number Diff line number Diff line change
Expand Up @@ -525,6 +525,16 @@ func (t *Type) arrayKeywords(tags []string) {
case "uniqueItems":
t.UniqueItems = true
}
} else {
name := nameValue[0]
switch name {
case "allowNull":
t.OneOf = []*Type{
{Type: t.Type},
{Type: "null"},
}
t.Type = ""
}
}
}
}
Expand Down
1 change: 1 addition & 0 deletions reflect_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ var schemaGenerationTests = []testSet{
{&jsonschema.Reflector{}, "fixtures/test_min_max_items.json", testmodels.SliceTestType{}},
{&jsonschema.Reflector{}, "fixtures/test_recursion.json", testmodels.TestFamilyMember{}},
{&jsonschema.Reflector{}, "fixtures/duplicate_embedded_fields.json", testmodels.Root{}},
{&jsonschema.Reflector{}, "fixtures/arrays.json", testmodels.Arrays{}},
}

func TestSchemaGeneration(t *testing.T) {
Expand Down
5 changes: 2 additions & 3 deletions subschemas_switch.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,6 @@ type SchemaSwitch struct {

var schemaCaseType = reflect.TypeOf((*schemaCase)(nil)).Elem()


// Appends jsonschema rules from Case interface to the jsonschema for the struct that implements them
func (r *Reflector) addSubschemasForSwitch(st *Type, definitions Definitions, t reflect.Type) {
if st == nil {
Expand All @@ -65,8 +64,8 @@ func (r *Reflector) addSubschemasForSwitch(st *Type, definitions Definitions, t
func (r *Reflector) reflectCases(definitions Definitions, sc SchemaSwitch) []*Type {
//Build order when not provided my the user of this library
if len(sc.Order) == 0 {
for key := range sc.Cases{
sc.Order = append(sc.Order,key)
for key := range sc.Cases {
sc.Order = append(sc.Order, key)
}
}
casesList := make([]*Type, 0)
Expand Down

0 comments on commit 333ed5c

Please sign in to comment.