diff --git a/field_parser.go b/field_parser.go index 500e2f4e4..b688d7639 100644 --- a/field_parser.go +++ b/field_parser.go @@ -141,6 +141,7 @@ type structField struct { defaultValue interface{} extensions map[string]interface{} enums []interface{} + enumVarNames []interface{} readOnly bool unique bool } @@ -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) @@ -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 } diff --git a/field_parser_test.go b/field_parser_test.go index 0dc0d6125..07b803d19 100644 --- a/field_parser_test.go +++ b/field_parser_test.go @@ -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()