Files
genqlient/generate/unmarshal_helper.go.tmpl
T
Ben KraftandGitHub 46898ca52c Return clearer errors when __typename is missing (#68)
## Summary:
In practice, at Khan at least, this is easy to mess up when writing
mocks, because you write the mock by looking at the query, and the query
doesn't say it's asking for `__typename` (because genqlient
automatically adds that).  A sufficiently-smart mocking library might be
able to fix that, or detect it at least, but in any case, we can give a
clearer error.

I also removed an unrelated TODO that was done.

Issue: https://khanacademy.slack.com/archives/C01120CNCS0/p1630019788014000

## Test plan:
make check


Author: benjaminjkraft

Reviewers: dnerdy, aberkan, csilvers, MiguelCastillo

Required Reviewers: 

Approved by: dnerdy

Checks:  Test (1.17),  Test (1.16),  Test (1.15),  Test (1.14),  Test (1.13),  Lint,  Test (1.17),  Test (1.16),  Test (1.15),  Test (1.14),  Test (1.13),  Lint

Pull request URL: https://github.com/Khan/genqlient/pull/68
2021-08-27 18:12:35 -07:00

34 lines
1.0 KiB
Cheetah

{{/* (the blank lines at the start are intentional, to separate
the helper from the function it follows) */}}
func __unmarshal{{.GoName}}(v *{{.GoName}}, m {{ref "encoding/json.RawMessage"}}) error {
if string(m) == "null" {
return nil
}
var tn struct {
TypeName string `json:"__typename"`
}
err := {{ref "encoding/json.Unmarshal"}}(m, &tn)
if err != nil {
return err
}
switch tn.TypeName {
{{range .Implementations -}}
case "{{.GraphQLName}}":
*v = new({{.GoName}})
return {{ref "encoding/json.Unmarshal"}}(m, *v)
{{end -}}
case "":
{{/* Likely if we're making a request to a mock server and the author
of the mock didn't know to add __typename, so give a special
error. */ -}}
return {{ref "fmt.Errorf"}}(
"Response was missing {{.GraphQLName}}.__typename")
default:
return {{ref "fmt.Errorf"}}(
`Unexpected concrete type for {{.GoName}}: "%v"`, tn.TypeName)
}
}