Skip to content

Commit

Permalink
Merge a9337d3 into 4f32ae6
Browse files Browse the repository at this point in the history
  • Loading branch information
rast1025 authored Dec 21, 2021
2 parents 4f32ae6 + a9337d3 commit ea33b4a
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 2 deletions.
18 changes: 16 additions & 2 deletions field_parser.go
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,7 @@ type structField struct {
defaultValue interface{}
extensions map[string]interface{}
enums []interface{}
enumVarNames []interface{}
readOnly bool
unique bool
}
Expand Down Expand Up @@ -236,7 +237,21 @@ func (ps *tagBaseFieldParser) ComplementSchema(schema *spec.Schema) error {
structField.enums = append(structField.enums, value)
}
}

varnamesTag := ps.tag.Get("x-enum-varnames")
if varnamesTag != "" {
if structField.extensions == nil {
structField.extensions = map[string]interface{}{}
}
varNames := strings.Split(varnamesTag, ",")
if len(varNames) != len(structField.enums) {
return fmt.Errorf("invalid count of x-enum-varnames. expected %d, got %d", len(structField.enums), len(varNames))
}
structField.enumVarNames = nil
for _, v := range varNames {
structField.enumVarNames = append(structField.enumVarNames, v)
}
structField.extensions["x-enum-varnames"] = structField.enumVarNames
}
defaultTag := ps.tag.Get("default")
if defaultTag != "" {
value, err := defineType(structField.schemaType, defaultTag)
Expand Down Expand Up @@ -345,7 +360,6 @@ func (ps *tagBaseFieldParser) ComplementSchema(schema *spec.Schema) error {
eleSchema.MaxLength = structField.maxLength
eleSchema.MinLength = structField.minLength
eleSchema.Enum = structField.enums

return nil
}

Expand Down
28 changes: 28 additions & 0 deletions field_parser_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,34 @@ func TestDefaultFieldParser(t *testing.T) {
assert.Error(t, err)
})

t.Run("EnumVarNames tag", func(t *testing.T) {
t.Parallel()

schema := spec.Schema{}
schema.Type = []string{"int"}
schema.Extensions = map[string]interface{}{}
schema.Enum = []interface{}{}
err := newTagBaseFieldParser(
&Parser{},
&ast.Field{Tag: &ast.BasicLit{
Value: `json:"test" enums:"0,1,2" x-enum-varnames:"Daily,Weekly,Monthly"`,
}},
).ComplementSchema(&schema)
schema.Extensions.Add("x-enum-varnames", []string{"Daily", "Weekly", "Monthly"})
assert.NoError(t, err)
assert.Equal(t, []string{"Daily", "Weekly", "Monthly"}, schema.Extensions["x-enum-varnames"])

schema = spec.Schema{}
schema.Type = []string{"int"}
err = newTagBaseFieldParser(
&Parser{},
&ast.Field{Tag: &ast.BasicLit{
Value: `json:"test" enums:"0,1,2,3" x-enum-varnames:"Daily,Weekly,Monthly"`,
}},
).ComplementSchema(&schema)
assert.Error(t, err)
})

t.Run("Default tag", func(t *testing.T) {
t.Parallel()

Expand Down

0 comments on commit ea33b4a

Please sign in to comment.