github.com/opiuman/genqlient@v1.0.0/generate/unmarshal_helper.go.tmpl (about) 1 {{/* This template generates a helper for each interface type genqlient must 2 unmarshal. This helper is called by the UnmarshalJSON of each (struct) 3 type with a field of the interface type, similar to how it calls custom 4 unmarshalers. The helper itself is fairly simple: it just parses out and 5 switches on __typename, then unmarshals into the relevant struct. */}} 6 7 func __unmarshal{{.GoName}}(b []byte, v *{{.GoName}}) error { 8 if string(b) == "null" { 9 return nil 10 } 11 12 var tn struct { 13 TypeName string `json:"__typename"` 14 } 15 err := {{ref "encoding/json.Unmarshal"}}(b, &tn) 16 if err != nil { 17 return err 18 } 19 20 switch tn.TypeName { 21 {{range .Implementations -}} 22 case "{{.GraphQLName}}": 23 *v = new({{.GoName}}) 24 return {{ref "encoding/json.Unmarshal"}}(b, *v) 25 {{end -}} 26 case "": 27 {{/* Likely if we're making a request to a mock server and the author 28 of the mock didn't know to add __typename, so give a special 29 error. */ -}} 30 return {{ref "fmt.Errorf"}}( 31 "response was missing {{.GraphQLName}}.__typename") 32 default: 33 return {{ref "fmt.Errorf"}}( 34 `unexpected concrete type for {{.GoName}}: "%v"`, tn.TypeName) 35 } 36 }