Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(go): Unions include runtime validation #5403

Merged
merged 2 commits into from
Dec 12, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 60 additions & 0 deletions generators/go/internal/generator/model.go
Original file line number Diff line number Diff line change
Expand Up @@ -474,6 +474,9 @@ func (t *typeVisitor) VisitUnion(union *ir.UnionTypeDeclaration) error {

// Implement the json.Marshaler interface.
t.writer.P("func (", receiver, " ", t.typeName, ") MarshalJSON() ([]byte, error) {")
t.writer.P("if err := ", receiver, ".validate(); err != nil {")
t.writer.P("return nil, err")
t.writer.P("}")
if t.unionVersion != UnionVersionV1 {
t.writer.P("switch ", receiver, ".", discriminantName, " {")
}
Expand Down Expand Up @@ -659,6 +662,63 @@ func (t *typeVisitor) VisitUnion(union *ir.UnionTypeDeclaration) error {
t.writer.P("}")
t.writer.P()

// Generate the validate method.
t.writer.P("func (", receiver, " *", t.typeName, ") validate() error {")
t.writer.P("if ", receiver, " == nil {")
t.writer.P(`return fmt.Errorf("type %T is nil", `, receiver, ")")
t.writer.P("}")
t.writer.P("var fields []string")
for _, unionType := range union.Types {
var (
isLiteral bool
isOptional bool
date *date
)
if unionType.Shape.SingleProperty != nil {
isLiteral = isLiteralType(unionType.Shape.SingleProperty.Type, t.writer.types)
isOptional = isOptionalType(unionType.Shape.SingleProperty.Type, t.writer.types)
date = maybeDate(unionType.Shape.SingleProperty.Type, isOptional)
}
zeroValue := "nil"
if unionType.Shape.PropertiesType == "singleProperty" {
zeroValue = zeroValueForTypeReference(unionType.Shape.SingleProperty.Type, t.writer.types)
}
unionTypeValue := receiver + "." + unionType.DiscriminantValue.Name.PascalCase.UnsafeName
if isLiteral {
unionTypeValue = receiver + "." + unionType.DiscriminantValue.Name.CamelCase.SafeName
}
if date != nil && !isOptional {
t.writer.P("if !", unionTypeValue, ".IsZero() {")
} else {
t.writer.P("if ", unionTypeValue, " != ", zeroValue, " {")
}
t.writer.P(`fields = append(fields, "`, unionType.DiscriminantValue.WireValue, `")`)
t.writer.P("}")
}
t.writer.P("if len(fields) == 0 {")
t.writer.P("if ", receiver, ".", discriminantName, ` != "" {`)
t.writer.P(`return fmt.Errorf("type %T defines a discriminant set to %q but the field is not set", `, receiver, ", ", receiver, ".", discriminantName, ")")
t.writer.P("}")
t.writer.P(`return fmt.Errorf("type %T is empty", `, receiver, ")")
t.writer.P("}")
t.writer.P("if len(fields) > 1 {")
t.writer.P(`return fmt.Errorf("type %T defines values for %s, but only one value is allowed", `, receiver, ", fields)")
t.writer.P("}")
t.writer.P("if ", receiver, ".", discriminantName, ` != "" {`)
t.writer.P("field := fields[0]")
t.writer.P("if ", receiver, ".", discriminantName, " != field {")
t.writer.P("return fmt.Errorf(")
t.writer.P(`"type %T defines a discriminant set to %q, but it does not match the %T field; either remove or update the discriminant to match",`)
t.writer.P(receiver, ", ")
t.writer.P(receiver, ".", discriminantName, ", ")
t.writer.P(receiver, ", ")
t.writer.P(")")
t.writer.P("}")
t.writer.P("}")
t.writer.P("return nil")
t.writer.P("}")
t.writer.P()

return nil
}

Expand Down
29 changes: 29 additions & 0 deletions generators/go/sdk/versions.yml
Original file line number Diff line number Diff line change
@@ -1,3 +1,32 @@
- version: 0.35.0
changelogEntry:
- type: feat
summary: >-
Add runtime validation for discriminated unions to prevent users from accidentally
sending the wrong type of value. With this, users will be expected to set exactly
one of the union's values like so:

```go
package example

type Animal struct {
Type string
Cat *Cat
Dog *Dog
}

func do() {
union := &Animal{
Cat: &Cat{
Name: "Fluffy",
},
}
}
```

If the user sets _both_ `Cat` and `Dog`, the user will receive an error when the
type is serialized to JSON (i.e. in the `json.Marshaler` implementation).
irVersion: 53
- version: 0.34.0
changelogEntry:
- type: feat
Expand Down
77 changes: 77 additions & 0 deletions seed/go-fiber/circular-references-advanced/ast.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

77 changes: 77 additions & 0 deletions seed/go-fiber/circular-references/ast.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading
Loading