Autogenerated models with unions cannot be unmarshaled
- 主要语言
- Go
- 星标
- 10.8k
- 派生
- 1.3k
- 平均合并
- 2 天 36 分钟
- 30 天内合并 PR
- 26
描述
### What happened?
https://github.com/99designs/gqlgen/issues/1055 is still reproducible.
### What did you expect?
Calling `json.Unmarshal` on union types will not cause panics after @vektah https://github.com/99designs/gqlgen/issues/1055#issuecomment-618753611.
### Minimal graphql.schema and models to reproduce
See repro at https://github.com/minkezhang/gqlgen-union-repro.
```bash
$ go test ./...
? github.com/minkezhang/gqlgen-union-repro/graph [no test files]
--- FAIL: TestUnmarshalJSON (0.00s)
--- FAIL: TestUnmarshalJSON/EmptyBaz (0.00s)
models_gen_test.go:44: json: cannot unmarshal object into Go struct field Data.baz of type model.Baz
--- FAIL: TestUnmarshalJSON/BazTypeFoo (0.00s)
models_gen_test.go:44: json: cannot unmarshal object into Go struct field Data.baz of type model.Baz
--- FAIL: TestUnmarshalJSON/BazTypeFooWithTypename (0.00s)
models_gen_test.go:44: json: cannot unmarshal object into Go struct field Data.baz of type model.Baz
FAIL
FAIL github.com/minkezhang/gqlgen-union-repro/graph/model 0.002s
FAIL
```
#### Schema
[schema.graphqls](https://github.com/minkezhang/gqlgen-union-repro/blob/main/graph/schema.graphqls)
```gql
type Foo {
foo: ID!
}
type Bar {
bar: ID!
}
union Baz = Foo | Bar
type Data {
baz: Baz!
}
```
#### Models
[model_gen.go](https://github.com/minkezhang/gqlgen-union-repro/blob/main/graph/model/models_gen.go)
```go
package model
type Baz interface {
IsBaz()
}
type Bar struct {
Bar string `json:"bar"`
}
func (Bar) IsBaz() {}
type Data struct {
Baz Baz `json:"baz"`
}
type Foo struct {
Foo string `json:"foo"`
}
func (Foo) IsBaz() {}
```
#### Test
[model_gen_test.go](https://github.com/minkezhang/gqlgen-union-repro/blob/main/graph/model/models_gen_test.go)
```go
package model
import (
"encoding/json"
"testing"
)
func TestUnmarshalJSON(t *testing.T) {
for _, c := range []struct {
name string
marshalled []byte
}{
{
name: "Empty",
marshalled: []byte("{}"),
},
{
name: "EmptyBaz",
marshalled: []byte(`{
"baz": {}
}`),
},
{
name: "BazTypeFoo",
marshalled: []byte(`{
"baz": {
"foo": "some-data"
}
}`),
},
{
name: "BazTypeFooWithTypename",
marshalled: []byte(`{
"baz": {
"__typename": "Foo",
"foo": "some-data"
}
}`),
},
} {
t.Run(c.name, func(t *testing.T) {
d := Data{}
if err := json.Unmarshal(c.marshalled, &d); err != nil {
t.Fatal(err)
}
})
}
}
```
### versions
- `go run github.com/99designs/gqlgen version`? v0.17.35
- `go version`? go version go1.20.6 linux/amd64
贡献指南
评估
这个 Issue 还没有评估数据。