Skip to content

Commit

Permalink
Merge pull request #231 from Yamashou/unmarshalgql5
Browse files Browse the repository at this point in the history
Request MarshalGQL
  • Loading branch information
Yamashou authored Jul 4, 2024
2 parents d1c1482 + 747916a commit eb9f086
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 3 deletions.
12 changes: 10 additions & 2 deletions clientv2/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -396,12 +396,12 @@ func (c *Client) unmarshal(data []byte, res interface{}) error {

func MarshalJSON(v interface{}) ([]byte, error) {
if v == nil {
return []byte("null"), nil // Directly return "null" for nil interface{}
return []byte("null"), nil
}

val := reflect.ValueOf(v)
if !val.IsValid() || (val.Kind() == reflect.Ptr && val.IsNil()) {
return []byte("null"), nil // Return "null" for nil pointer or invalid reflect value
return []byte("null"), nil
}

return encode(val)
Expand All @@ -417,6 +417,10 @@ func checkImplements[I any](v reflect.Value) bool {

// encode returns an appropriate encoder function for the provided value.
func encode(v reflect.Value) ([]byte, error) {
if !v.IsValid() || (v.Kind() == reflect.Ptr && v.IsNil()) {
return []byte("null"), nil
}

if checkImplements[graphql.Marshaler](v) {
return encodeGQLMarshaler(v.Interface())
}
Expand Down Expand Up @@ -457,6 +461,10 @@ func encode(v reflect.Value) ([]byte, error) {
}

func encodeGQLMarshaler(v any) ([]byte, error) {
if v == nil {
return []byte("null"), nil
}

var buf bytes.Buffer
if val, ok := v.(graphql.Marshaler); ok {
val.MarshalGQL(&buf)
Expand Down
16 changes: 15 additions & 1 deletion clientv2/client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -579,6 +579,8 @@ func TestMarshalJSON(t *testing.T) {
Number Number `json:"number"`
}

var b *Number

// example nested struct
type WhereInput struct {
Not *WhereInput `json:"not,omitempty"`
Expand Down Expand Up @@ -640,6 +642,18 @@ func TestMarshalJSON(t *testing.T) {
},
want: []byte(`{"operationName":"query", "query":"query ($input: Number!) { input }","variables":{"where":{"not":{"id":"1"}}}}`),
},
{
name: "marshal nil",
args: args{
v: Request{
OperationName: "query",
Variables: map[string]any{
"v": b,
},
},
},
want: []byte(`{"operationName":"query", "query":"","variables":{"v":null}}`),
},
{
name: "marshal a struct with custom marshaler",
args: args{
Expand Down Expand Up @@ -738,7 +752,7 @@ func TestMarshalJSON(t *testing.T) {
return
}
if err := json.Unmarshal(tt.want, &wantMap); err != nil {
t.Errorf("Failed to unmarshal 'want': %s", tt.want)
t.Errorf("Failed to unmarshal err: %s", err)
return
}

Expand Down

0 comments on commit eb9f086

Please sign in to comment.