openapi-generator-go icon indicating copy to clipboard operation
openapi-generator-go copied to clipboard

feat: add support for default values

Open injeniero opened this issue 1 year ago • 2 comments

This PR implements support for the "default" property. The implementation details are as follow:

  • Object: the provided value is used as JSON and will be unmarshaled to an Object instance.
  • ObjectProperties: Default values are given in the Factory function of the Containing Object.
  • Simple Named types: Default value is stored in a variable named Default{TypeName}.
  • Enum: Default value is stored in a variable named Default{TypeName}.
  • OneOf: Default value is not supported in the main Object, but each referenced type can have their default.

Examples

For a full example please go to: Default

Pet:
  type: object
  properties:
    type:
      $ref: '#/components/schemas/PetType'
    name:
      type: string
    age:
      type: integer
      default: 1
  default:
    type: dog
    name: Fido
    age: 2
// NewPet instantiates a new Pet with default values overriding them as follows:
// 1. Default values specified in the Pet schema
// 2. Default values specified per Pet property
func NewPet() *Pet {
	m := &Pet{
		Age:  1,
		Type: DefaultPetType,
	}

	type alias Pet
	err := json.Unmarshal([]byte(`{"age":2,"name":"Fido","type":"dog"}`), (*alias)(m))
	if err != nil {
		panic(fmt.Errorf("could not unmarshal default values for Pet: %w", err))
	}

	return m
}

[!IMPORTANT] A side effect of this PR is moving inline structs to named types. This was required to properly support validation and default handling without needing to have a special case for them.

Ticket

#136

How Has This Been Verified?

Unit tests

Checklist:

  • [x] The change works as expected.
  • [ ] New code can be debugged via logs.
  • [x] I have added tests to cover my changes.
  • [x] I have locally run the tests and all new and existing tests passed.
  • [x] Requires updates to the documentation.
  • [ ] I have made the required changes to the documents.

injeniero avatar Feb 26 '24 21:02 injeniero

@LucasRoesler pinging you, just make sure you saw this. Thanks!!

injeniero avatar Feb 27 '24 23:02 injeniero

@injeniero I am so sorry, i saw this and then it slipped off my list. There were a few offline events happening and it distracted me. I am going to read through this today

LucasRoesler avatar Mar 24 '24 11:03 LucasRoesler