Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Default required #1181

Merged
merged 7 commits into from Jun 16, 2022
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
3 changes: 2 additions & 1 deletion README.md
Expand Up @@ -99,6 +99,7 @@ OPTIONS:
--codeExampleFiles value, --cef value Parse folder containing code example files to use for the x-codeSamples extension, disabled by default
--parseInternal Parse go files in internal packages, disabled by default (default: false)
--generatedTime Generate timestamp at the top of docs.go, disabled by default (default: false)
--defaultRequired Set validation required for all fields by default (default: false)
--parseDepth value Dependency parse depth (default: 100)
--instanceName value This parameter can be used to name different swagger document instances. It is optional.
--overridesFile value File to read global type overrides from. (default: ".swaggo")
Expand Down Expand Up @@ -487,7 +488,7 @@ type Foo struct {

Field Name | Type | Description
---|:---:|---
<a name="validate"></a>validate | `string` | Determines the validation for the parameter. Possible values are: `required`.
<a name="validate"></a>validate | `string` | Determines the validation for the parameter. Possible values are: `required,optional`.
<a name="parameterDefault"></a>default | * | Declares the value of the parameter that the server will use if none is provided, for example a "count" to control the number of results per page might default to 100 if not supplied by the client in the request. (Note: "default" has no meaning for required parameters.) See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-6.2. Unlike JSON Schema this value MUST conform to the defined [`type`](#parameterType) for this parameter.
<a name="parameterMaximum"></a>maximum | `number` | See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.2.
<a name="parameterMinimum"></a>minimum | `number` | See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.3.
Expand Down
6 changes: 6 additions & 0 deletions cmd/swag/main.go
Expand Up @@ -26,6 +26,7 @@ const (
codeExampleFilesFlag = "codeExampleFiles"
parseInternalFlag = "parseInternal"
generatedTimeFlag = "generatedTime"
defaultRequiredFlag = "defaultRequired"
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think "requiredByDefault" sounds better.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed

parseDepthFlag = "parseDepth"
instanceNameFlag = "instanceName"
overridesFileFlag = "overridesFile"
Expand Down Expand Up @@ -100,6 +101,10 @@ var initFlags = []cli.Flag{
Value: 100,
Usage: "Dependency parse depth",
},
&cli.BoolFlag{
Name: defaultRequiredFlag,
Usage: "Set validation required for all fields by default",
},
&cli.StringFlag{
Name: instanceNameFlag,
Value: "",
Expand Down Expand Up @@ -138,6 +143,7 @@ func initAction(c *cli.Context) error {
MarkdownFilesDir: c.String(markdownFilesFlag),
ParseInternal: c.Bool(parseInternalFlag),
GeneratedTime: c.Bool(generatedTimeFlag),
DefaultRequired: c.Bool(defaultRequiredFlag),
CodeExampleFilesDir: c.String(codeExampleFilesFlag),
ParseDepth: c.Int(parseDepthFlag),
InstanceName: c.String(instanceNameFlag),
Expand Down
12 changes: 9 additions & 3 deletions field_parser.go
Expand Up @@ -439,22 +439,28 @@ func (ps *tagBaseFieldParser) IsRequired() (bool, error) {
bindingTag := ps.tag.Get(bindingTag)
if bindingTag != "" {
for _, val := range strings.Split(bindingTag, ",") {
if val == "required" {
switch val {
case "required":
return true, nil
case "optional":
return false, nil
}
}
}

validateTag := ps.tag.Get(validateTag)
if validateTag != "" {
for _, val := range strings.Split(validateTag, ",") {
if val == "required" {
switch val {
case "required":
return true, nil
case "optional":
return false, nil
}
}
}

return false, nil
return ps.p.DefaultRequired, nil
}

func (ps *tagBaseFieldParser) parseValidTags(validTag string, sf *structField) {
Expand Down
41 changes: 41 additions & 0 deletions field_parser_test.go
Expand Up @@ -82,6 +82,47 @@ func TestDefaultFieldParser(t *testing.T) {
assert.Equal(t, true, got)
})

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

got, err := newTagBaseFieldParser(
&Parser{
DefaultRequired: true,
},
&ast.Field{Tag: &ast.BasicLit{
Value: `json:"test"`,
}},
).IsRequired()
assert.NoError(t, err)
assert.True(t, got)
})

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

got, err := newTagBaseFieldParser(
&Parser{
DefaultRequired: true,
},
&ast.Field{Tag: &ast.BasicLit{
Value: `json:"test" binding:"optional"`,
}},
).IsRequired()
assert.NoError(t, err)
assert.False(t, got)

got, err = newTagBaseFieldParser(
&Parser{
DefaultRequired: true,
},
&ast.Field{Tag: &ast.BasicLit{
Value: `json:"test" validate:"optional"`,
}},
).IsRequired()
assert.NoError(t, err)
assert.False(t, got)
})

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

Expand Down
4 changes: 4 additions & 0 deletions gen/gen.go
Expand Up @@ -105,6 +105,9 @@ type Config struct {
// GeneratedTime whether swag should generate the timestamp at the top of docs.go
GeneratedTime bool

// DefaultRequired set validation required for all fields by default
DefaultRequired bool

// OverridesFile defines global type overrides.
OverridesFile string
}
Expand Down Expand Up @@ -151,6 +154,7 @@ func (g *Gen) Build(config *Config) error {
p.ParseVendor = config.ParseVendor
p.ParseDependency = config.ParseDependency
p.ParseInternal = config.ParseInternal
p.DefaultRequired = config.DefaultRequired

if err := p.ParseAPIMultiSearchDir(searchDirs, config.MainAPIFile, config.ParseDepth); err != nil {
return err
Expand Down
2 changes: 2 additions & 0 deletions go.sum
Expand Up @@ -60,6 +60,8 @@ github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UV
github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/swaggo/swag v1.8.1 h1:JuARzFX1Z1njbCGz+ZytBR15TFJwF2Q7fu8puJHhQYI=
github.com/swaggo/swag v1.8.1/go.mod h1:ugemnJsPZm/kRwFUnzBlbHRd0JY9zE1M4F+uy2pAaPQ=
github.com/urfave/cli/v2 v2.3.0 h1:qph92Y649prgesehzOrQjdWyxFOp/QVM+6imKHad91M=
github.com/urfave/cli/v2 v2.3.0/go.mod h1:LJmUH05zAU44vOAcrfzZQKsZbVcdbOG8rtL3/XcUArI=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
Expand Down
3 changes: 3 additions & 0 deletions parser.go
Expand Up @@ -117,6 +117,9 @@ type Parser struct {
// Strict whether swag should error or warn when it detects cases which are most likely user errors
Strict bool

// DefaultRequired set validation required for all fields by default
DefaultRequired bool

// structStack stores full names of the structures that were already parsed or are being parsed now
structStack []*TypeSpecDef

Expand Down