From 34b3268687c0d77a4ae9679fd2a9e9a19eb67a8b Mon Sep 17 00:00:00 2001 From: Florent CHAUVEAU Date: Fri, 15 Jul 2022 17:53:12 +0200 Subject: [PATCH] New compatibility option to mark readOnly+required fields as non pointers This fixes #604. --- pkg/codegen/configuration.go | 4 ++++ pkg/codegen/schema.go | 6 ++++-- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/pkg/codegen/configuration.go b/pkg/codegen/configuration.go index c8530c8ea..2b746400c 100644 --- a/pkg/codegen/configuration.go +++ b/pkg/codegen/configuration.go @@ -57,6 +57,10 @@ type CompatibilityOptions struct { // When an object contains no members, and only an additionalProperties specification, // it is flattened to a map. Set DisableFlattenAdditionalProperties bool `yaml:"disable-flatten-additional-properties,omitempty"` + // When an object property is both required and readOnly the go model is generated + // as a pointer. Set DisableRequiredReadOnlyAsPointer to true to mark them as non pointer. + // Please see https://github.com/deepmap/oapi-codegen/issues/604 + DisableRequiredReadOnlyAsPointer bool `yaml:"disable-required-readonly-as-pointer,omitempty"` } // OutputOptions are used to modify the output code in some way. diff --git a/pkg/codegen/schema.go b/pkg/codegen/schema.go index f8da94f40..c1c450076 100644 --- a/pkg/codegen/schema.go +++ b/pkg/codegen/schema.go @@ -94,7 +94,9 @@ func (p Property) GoFieldName() string { func (p Property) GoTypeDef() string { typeDef := p.Schema.TypeDecl() if !p.Schema.SkipOptionalPointer && - (!p.Required || p.Nullable || p.ReadOnly || p.WriteOnly) { + (!p.Required || p.Nullable || + (p.ReadOnly && (!p.Required || !globalState.options.Compatibility.DisableRequiredReadOnlyAsPointer)) || + p.WriteOnly) { typeDef = "*" + typeDef } @@ -592,7 +594,7 @@ func GenFieldsFromProperties(props []Property) []string { fieldTags := make(map[string]string) - if (p.Required && !p.ReadOnly && !p.WriteOnly) || p.Nullable || !overrideOmitEmpty { + if (p.Required && !p.ReadOnly && !p.WriteOnly) || p.Nullable || !overrideOmitEmpty || (p.Required && p.ReadOnly && globalState.options.Compatibility.DisableRequiredReadOnlyAsPointer) { fieldTags["json"] = p.JsonFieldName if p.NeedsFormTag { fieldTags["form"] = p.JsonFieldName