Skip to content

Bad JSON marshaling for custom Marshaler #471

@ghost

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.Marshalreturns the expected JSON output.

Expected Result (Simple json.Marshal)

{
    "mobile": "1234567891"
}

Current Result (GraphQL response)

{
    "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.

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions