Skip to content

Commit 434972e

Browse files
committed
generate: set omitzero on specific types
Set `omitzero` on the following types to allow clients to set an empty slice and have it serialized to `[]`, which is required by Oxide APIs to unset a value. * `[]VpcFirewallRuleUpdate` * `[]NameOrId` The previous behavior would omit an empty slice entirely during serialization, causing the Oxide APIs to respond with an error.
1 parent 2e4943b commit 434972e

File tree

3 files changed

+23
-3
lines changed

3 files changed

+23
-3
lines changed

internal/generate/exceptions.go

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,15 @@
44

55
package main
66

7+
// omitzeroTypes returns a slice of types that should be tagged with omitzero
8+
// for serialization and deserialization.
9+
func omitzeroTypes() []string {
10+
return []string{
11+
"[]VpcFirewallRuleUpdate",
12+
"[]NameOrId",
13+
}
14+
}
15+
716
func emptyTypes() []string {
817
return []string{
918
"BgpMessageHistory",

internal/generate/types.go

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -542,9 +542,20 @@ func createTypeObject(schema *openapi3.Schema, name, typeName, description strin
542542
field.Name = strcase.ToCamel(k)
543543
field.Type = typeName
544544

545+
// TODO: Set omitzero on all types.
546+
// Long-term, omitzero should be set on all types, even nullable arrays.
547+
// In https://spec.openapis.org/oas/v3.0.4.html#appendix-b-data-type-conversion,
548+
// which is one patch version ahead of Nexus' OpenAPI specification at the time
549+
// of this writing, it notes that null is treated as undefined. That suggests
550+
// that an omitted JSON attribute is treated the same as setting it to null.
551+
//
552+
// For now though, only set omitzero on certain types that are confirmed to be
553+
// safe when omitted (e.g., types defined by omitzeroTypes).
545554
serInfo := fmt.Sprintf("`json:\"%s,omitempty\" yaml:\"%s,omitempty\"`", k, k)
546555
if isNullableArray(v) {
547556
serInfo = fmt.Sprintf("`json:\"%s\" yaml:\"%s\"`", k, k)
557+
} else if sliceContains(omitzeroTypes(), typeName) {
558+
serInfo = fmt.Sprintf("`json:\"%s,omitzero\" yaml:\"%s,omitzero\"`", k, k)
548559
}
549560

550561
field.SerializationInfo = serInfo

oxide/types.go

Lines changed: 3 additions & 3 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)