Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Redefining scalar ID #693

Open
llonchj opened this issue May 7, 2024 · 0 comments
Open

Redefining scalar ID #693

llonchj opened this issue May 7, 2024 · 0 comments

Comments

@llonchj
Copy link

llonchj commented May 7, 2024

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!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant