graphql-go / graphql

An implementation of GraphQL for Go / Golang
MIT License
9.82k stars 836 forks source link

Redefining scalar ID #693

Open llonchj opened 2 months ago

llonchj commented 2 months ago

I am writting a graphql server with all the ID of type uuid.UUID (github.com/google/uuid) and it is required to support Global Object Identification (https://graphql.org/learn/global-object-identification).

To avoid having to parse the ID as string, getting it directly as uuid.UUID, I would like to redefine the ID scalar with this code:

package uuid

import (
    "fmt"

    "github.com/graphql-go/graphql"
    "github.com/graphql-go/graphql/language/ast"
)

func GraphQLScalar(name string) *graphql.Scalar {
    return graphql.NewScalar(graphql.ScalarConfig{
        Name:        name,
        Description: fmt.Sprintf("The `%s` scalar type represents an UUID Object.", name),
        // Serialize serializes `UUID` to string.
        Serialize: func(value interface{}) interface{} {
            switch value := value.(type) {
            case UUID:
                return value.String()
            case *UUID:
                return (*value).String()
            default:
                return nil
            }
        },
        // ParseValue parses GraphQL variables from `string` to `UUID`.
        ParseValue: func(value interface{}) interface{} {
            switch value := value.(type) {
            case string:
                u, _ := Parse(value)
                return u
            case *string:
                u, _ := Parse(*value)
                return u
            default:
                return nil
            }
        },
        // ParseLiteral parses GraphQL AST value to `UUID`.
        ParseLiteral: func(valueAST ast.Value) interface{} {
            switch valueAST := valueAST.(type) {
            case *ast.StringValue:
                u, _ := Parse(valueAST.Value)
                return u
            default:
                return nil
            }
        },
    })
}

Although, I get the error error: Schema must contain unique named types but contains multiple types named "ID".

  1. Is it a good practice to redefine the ID scalar?
  2. What is the best way to do it?

Thanks!