graphql-go / graphql-go/graphql

Bad JSON marshaling for custom Marshaler

Open
#471 10 comments 1 reaction 0 assignees View on GitHub
Dominant language
Go
Stars
10.1k
Forks
845
PR merge metrics
No merged PRs in 30d

Description

I am using the library `github.com/guregu/null` in order to provide an easy management of null fields on my database entities. The library provides the following structures:
- `null.String`
- `null.Int`
- `null.Bool`
- `null.Time`

Every structure implements **JSONMarshaler** and **JSONUnmarshaler** interfaces, so a simple `json.Marshal`returns the expected JSON output.

_Expected Result (Simple_ `json.Marshal`_)_
```json
{
"mobile": "1234567891"
}
```

_Current Result (GraphQL response)_
```json
{
"mobile": "{{1234567891 true}}"
}
```

I imagine that this happens because the structure has two exported fields (Value and Valid).
But this **should not happen** since the structure implements the JSON marshaler and unmarshaler interfaces.

I think that the problem is in `scalars.go` file. Take String scalar as example. The `coerceString` casts the string to a string pointer when the interface implements the Marshaler interface.
```go
func coerceString(value interface{}) interface{} {
if v, ok := value.(*string); ok {
if v == nil {
return nil
}
return *v
}
return fmt.Sprintf("%v", value)
}

// String is the GraphQL string type definition
var String = NewScalar(ScalarConfig{
Name: "String",
Description: "The `String` scalar type represents textual data, represented as UTF-8 " +
"character sequences. The String type is most often used by GraphQL to " +
"represent free-form human-readable text.",
Serialize: coerceString,
ParseValue: coerceString,
ParseLiteral: func(valueAST ast.Value) interface{} {
switch valueAST := valueAST.(type) {
case *ast.StringValue:
return valueAST.Value
}
return nil
},
})
```
I don't know what is the best practice for this library, but I would like to get help about this and provide a smart solution.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.