Skip to content

Commit

Permalink
implement pattern tag (#1553)
Browse files Browse the repository at this point in the history
Co-authored-by: Tobias Theel <[email protected]>
  • Loading branch information
Nerzal and Tobias Theel authored Apr 17, 2023
1 parent 44b59ad commit 543e18b
Show file tree
Hide file tree
Showing 5 changed files with 726 additions and 0 deletions.
8 changes: 8 additions & 0 deletions field_parser.go
Original file line number Diff line number Diff line change
Expand Up @@ -173,6 +173,7 @@ type structField struct {
enums []interface{}
enumVarNames []interface{}
unique bool
pattern string
}

// splitNotWrapped slices s into all substrings separated by sep if sep is not
Expand Down Expand Up @@ -337,6 +338,11 @@ func (ps *tagBaseFieldParser) complementSchema(schema *spec.Schema, types []stri
if minLength != nil {
field.minLength = minLength
}

pattern, ok := ps.tag.Lookup(patternTag)
if ok {
field.pattern = pattern
}
}

// json:"name,string" or json:",string"
Expand Down Expand Up @@ -445,6 +451,7 @@ func (ps *tagBaseFieldParser) complementSchema(schema *spec.Schema, types []stri
schema.MaxItems = field.maxItems
schema.MinItems = field.minItems
schema.UniqueItems = field.unique
schema.Pattern = field.pattern

eleSchema = schema.Items.Schema
eleSchema.Format = field.formatType
Expand All @@ -456,6 +463,7 @@ func (ps *tagBaseFieldParser) complementSchema(schema *spec.Schema, types []stri
eleSchema.MaxLength = field.maxLength
eleSchema.MinLength = field.minLength
eleSchema.Enum = field.enums
eleSchema.Pattern = field.pattern

return nil
}
Expand Down
44 changes: 44 additions & 0 deletions field_parser_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -668,4 +668,48 @@ func TestValidTags(t *testing.T) {
assert.NoError(t, err)
assert.Empty(t, schema.Enum)
})

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

schema := spec.Schema{}
schema.Type = []string{"array"}
schema.Items = &spec.SchemaOrArray{
Schema: &spec.Schema{
SchemaProps: spec.SchemaProps{
Type: []string{"string"},
},
},
}
err := newTagBaseFieldParser(
&Parser{},
&ast.Field{Tag: &ast.BasicLit{
Value: `json:"test" pattern:"^[a-zA-Z0-9_]*$"`,
}},
).ComplementSchema(&schema)
assert.NoError(t, err)
assert.Equal(t, "^[a-zA-Z0-9_]*$", schema.Pattern)
})

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

schema := spec.Schema{}
schema.Type = []string{"array"}
schema.Items = &spec.SchemaOrArray{
Schema: &spec.Schema{
SchemaProps: spec.SchemaProps{
Type: []string{"string"},
},
},
}
err := newTagBaseFieldParser(
&Parser{},
&ast.Field{Tag: &ast.BasicLit{
Value: `json:"test" pattern:"^[a-zA-Z0-9_]*$"`,
}},
).ComplementSchema(&schema)
assert.NoError(t, err)
assert.Equal(t, "^[a-zA-Z0-9_]*$", schema.Items.Schema.Pattern)
})
}
Loading

0 comments on commit 543e18b

Please sign in to comment.