-
Notifications
You must be signed in to change notification settings - Fork 141
Expand file tree
/
Copy pathmarshal_helper.go.tmpl
More file actions
61 lines (59 loc) · 2.2 KB
/
Copy pathmarshal_helper.go.tmpl
File metadata and controls
61 lines (59 loc) · 2.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
{{/* This is somewhat parallel to unmarshal_helper.go.tmpl, but, as usual, in
reverse. Note the helper accepts a pointer-to-interface, for
consistency with unmarshaling and with the API we expect of custom
marshalers. */}}
func __marshal{{.GoName}}(v *{{.GoName}}) ([]byte, error) {
{{/* Determine the GraphQL typename, which the unmarshaler will need should
it be called on our output. */}}
{{if .Implementations -}}
var typename string
{{end -}}
switch v := (*v).(type) {
{{range .Implementations -}}
case *{{.GoName}}:
typename = "{{.GraphQLName}}"
{{/* Now actually do the marshal, with the concrete type. (Go only
marshals embeds the way we want if they're structs.) Except that
won't work right if the implementation-type has its own
MarshalJSON method (maybe it in turn has an interface-typed
field), so we call the helper __premarshalJSON directly (see
marshal.go.tmpl). */}}
{{if .NeedsMarshaling -}}
premarshaled, err := v.__premarshalJSON()
if err != nil {
return nil, err
}
result := struct {
TypeName string `json:"__typename"`
*__premarshal{{.GoName}}
}{typename, premarshaled}
{{else -}}
result := struct {
TypeName string `json:"__typename"`
*{{.GoName}}
}{typename, v}
{{end -}}
return json.Marshal(result)
{{end -}}
{{if .OtherImplementation -}}
case *{{.OtherImplementation.GoName}}:
{{/* Catch-all from OmitUnreferencedImplementations. Its own
__typename field carries the GraphQL type-name, so no
wrapper struct is needed. */ -}}
{{if .OtherImplementation.NeedsMarshaling -}}
premarshaled, err := v.__premarshalJSON()
if err != nil {
return nil, err
}
return json.Marshal(premarshaled)
{{else -}}
return json.Marshal(v)
{{end -}}
{{end -}}
case nil:
return []byte("null"), nil
default:
return nil, {{ref "fmt.Errorf"}}(
`unexpected concrete type for {{.GoName}}: "%T"`, v)
}
}