Skip to content

Commit 44ddba3

Browse files
veleekdanicc097
authored andcommitted
Improve logic for x-omitempty (oapi-codegen#1033)
Currently x-omitempty only enables you to force the _absences_ of `omitempty`. This PR changes the logic so that the existance of `x-omitempty` will force omit empty to be whatever the user specifies. The logic around omit empty is pretty confusing here though. For example, why is omitEmpty excluded by default if it's nullable (e.g. if `p.Nullable` then `omitEmpty = false`).
1 parent 50c4e3e commit 44ddba3

1 file changed

Lines changed: 8 additions & 5 deletions

File tree

pkg/codegen/schema.go

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -638,17 +638,20 @@ func GenFieldsFromProperties(props []Property) []string {
638638

639639
field += fmt.Sprintf(" %s %s", goFieldName, p.GoTypeDef())
640640

641+
omitEmpty := !p.Nullable &&
642+
(!p.Required || p.ReadOnly || p.WriteOnly) &&
643+
(!p.Required || !p.ReadOnly || !globalState.options.Compatibility.DisableRequiredReadOnlyAsPointer)
644+
641645
// Support x-omitempty
642-
overrideOmitEmpty := true
643-
if _, ok := p.Extensions[extPropOmitEmpty]; ok {
644-
if extOmitEmpty, err := extParseOmitEmpty(p.Extensions[extPropOmitEmpty]); err == nil {
645-
overrideOmitEmpty = extOmitEmpty
646+
if extOmitEmptyValue, ok := p.Extensions[extPropOmitEmpty]; ok {
647+
if extOmitEmpty, err := extParseOmitEmpty(extOmitEmptyValue); err == nil {
648+
omitEmpty = extOmitEmpty
646649
}
647650
}
648651

649652
fieldTags := make(map[string]string)
650653

651-
if (p.Required && !p.ReadOnly && !p.WriteOnly) || p.Nullable || !overrideOmitEmpty || (p.Required && p.ReadOnly && globalState.options.Compatibility.DisableRequiredReadOnlyAsPointer) {
654+
if !omitEmpty {
652655
fieldTags["json"] = p.JsonFieldName
653656
if p.NeedsFormTag {
654657
fieldTags["form"] = p.JsonFieldName

0 commit comments

Comments
 (0)