swaggest / rest

Web services with OpenAPI and JSON Schema done quick in Go
https://pkg.go.dev/github.com/swaggest/rest
MIT License
362 stars 17 forks source link

Default value not applied when defined using schema.WithDefault #133

Closed pboguslawski closed 7 months ago

pboguslawski commented 1 year ago

Describe bug According to https://github.com/swaggest/rest/discussions/132#discussioncomment-4873894 it's possible to define default type value with schema.WithDefault like this

type SortDir string
func (s SortDir) PrepareJSONSchema(schema *jsonschema.Schema) error {
    schema.Enum = []interface{}{"asc", "desc"}
    schema.WithDefault("asc")
    schema.WithExamples("desc")
    return nil
}
type ItemListRequest struct {
[...]
   SortDir SortDir  `query:"sort_dir"`
}

but when

decoderFactory.ApplyDefaults = true

interactor input contains empty SortDir field for request without sort_dir specified (should be default value asc). After changing

-   SortDir SortDir  `query:"sort_dir"`
+   SortDir SortDir  `query:"sort_dir" default:"asc"`

request without sort_dir specified in query generate SortDir = asc in interactor input.

Expected behavior (1) SortDir default value asc should be applied for requests without sort_dir in query when default value is specified using schema.WithDefault (similar how default field tag works).

(2) When both schema.WithDefault and default field tag are specified, openapi.json does not contain default definition from tag, just schema reference #/components/schemas/SortDir so default definition from field tag should be ignored in such scenario probably but is not (as above).