-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmarshal.go
More file actions
190 lines (174 loc) · 4.45 KB
/
marshal.go
File metadata and controls
190 lines (174 loc) · 4.45 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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
package querybuilder
import (
"bytes"
"context"
"encoding/json"
"fmt"
"reflect"
"slices"
"sort"
"strings"
gqlgen "github.com/99designs/gqlgen/graphql"
"golang.org/x/sync/errgroup"
)
// GraphQLMarshaller is an internal interface for marshalling an object into GraphQL.
type GraphQLMarshaller interface {
// XXX_GraphQLType is an internal function. It returns the native GraphQL type name
XXX_GraphQLType() string
// XXX_GraphQLIDType is an internal function. It returns the native GraphQL type name for the ID of this object
XXX_GraphQLIDType() string
// XXX_GraphqlID is an internal function. It returns the underlying type ID
XXX_GraphQLID(ctx context.Context) (string, error)
json.Marshaler
}
const (
GraphQLMarshallerType = "XXX_GraphQLType"
GraphQLMarshallerIDType = "XXX_GraphQLIDType"
GraphQLMarshallerID = "XXX_GraphQLID"
)
type enum interface {
IsEnum()
Name() string
Value() string
}
var (
gqlMarshaller = reflect.TypeFor[GraphQLMarshaller]()
enumT = reflect.TypeFor[enum]()
)
func MarshalGQL(ctx context.Context, v any) (string, error) {
if v == nil {
return "null", nil
}
return marshalValue(ctx, reflect.ValueOf(v))
}
func marshalValue(ctx context.Context, v reflect.Value) (string, error) {
t := v.Type()
if t.Implements(gqlMarshaller) {
return marshalCustom(ctx, v)
}
if t.Implements(enumT) {
return marshalEnumName(v), nil
}
switch t.Kind() {
case reflect.Bool:
return fmt.Sprintf("%t", v.Bool()), nil
case reflect.Int:
return fmt.Sprintf("%d", v.Int()), nil
case reflect.Float32, reflect.Float64:
return fmt.Sprintf("%f", v.Float()), nil
case reflect.String:
if t.Implements(enumT) {
return marshalEnumName(v), nil
}
// escape strings following graphQL spec
// https://github.com/graphql/graphql-spec/blob/main/spec/Section%202%20--%20Language.md#string-value
var buf bytes.Buffer
gqlgen.MarshalString(v.String()).MarshalGQL(&buf)
return buf.String(), nil
case reflect.Pointer, reflect.Interface:
if v.IsNil() {
return "null", nil
}
return marshalValue(ctx, v.Elem())
case reflect.Slice:
n := v.Len()
elems := make([]string, n)
eg, gctx := errgroup.WithContext(ctx)
for i := range n {
eg.Go(func() error {
m, err := marshalValue(gctx, v.Index(i))
if err != nil {
return err
}
elems[i] = m
return nil
})
}
if err := eg.Wait(); err != nil {
return "", err
}
return fmt.Sprintf("[%s]", strings.Join(elems, ",")), nil
case reflect.Struct:
n := v.NumField()
elems := make([]string, n)
eg, gctx := errgroup.WithContext(ctx)
for i := range n {
eg.Go(func() error {
f := t.Field(i)
fv := v.Field(i)
name := f.Name
jsonTag := strings.Split(f.Tag.Get("json"), ",")
if jsonTag[0] != "" {
name = jsonTag[0]
}
isOptional := slices.Contains(jsonTag[1:], "omitempty")
if isOptional && IsZeroValue(fv.Interface()) {
return nil
}
m, err := marshalValue(gctx, fv)
if err != nil {
return err
}
if m != `""` && m != "null" {
elems[i] = fmt.Sprintf("%s:%s", name, m)
}
return nil
})
}
if err := eg.Wait(); err != nil {
return "", err
}
nonNullElems := make([]string, 0, n)
for _, elem := range elems {
if elem != "" {
nonNullElems = append(nonNullElems, elem)
}
}
return fmt.Sprintf("{%s}", strings.Join(nonNullElems, ",")), nil
case reflect.Map:
elems := make([]string, 0, v.Len())
for _, key := range v.MapKeys() {
m, err := marshalValue(ctx, v.MapIndex(key))
if err != nil {
return "", err
}
elems = append(elems, fmt.Sprintf("%s:%s", key, m))
}
sort.Strings(elems)
return fmt.Sprintf("{%s}", strings.Join(elems, ",")), nil
default:
return "", fmt.Errorf("unsupported argument of kind %s", t.Kind())
}
}
func marshalCustom(ctx context.Context, v reflect.Value) (string, error) {
result := v.MethodByName(GraphQLMarshallerID).Call([]reflect.Value{
reflect.ValueOf(ctx),
})
if len(result) != 2 {
panic(result)
}
err := result[1].Interface()
if err != nil {
return "", err.(error)
}
return fmt.Sprintf("%q", result[0].String()), nil
}
func marshalEnumName(v reflect.Value) string {
result := v.MethodByName("Name").Call(nil)
if len(result) != 1 {
panic(result)
}
return result[0].String()
}
func IsZeroValue(value any) bool {
v := reflect.ValueOf(value)
kind := v.Type().Kind()
switch kind {
case reflect.Pointer:
return v.IsNil()
case reflect.Slice, reflect.Array:
return v.Len() == 0
default:
return v.IsZero()
}
}