Skip to content

Commit

Permalink
Extract ID scalar implmentation
Browse files Browse the repository at this point in the history
This change moves the ID scalar implementation out of `graphql.go` and
into its own file `id.go` for consistency with the Time scalar
implementation.
  • Loading branch information
tonyghita authored and neelance committed Oct 14, 2017
1 parent 10eb949 commit d8c5743
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 23 deletions.
23 changes: 0 additions & 23 deletions graphql.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,6 @@ import (

"encoding/json"

"strconv"

"github.com/neelance/graphql-go/errors"
"github.com/neelance/graphql-go/internal/common"
"github.com/neelance/graphql-go/internal/exec"
Expand All @@ -21,27 +19,6 @@ import (
"github.com/neelance/graphql-go/trace"
)

// ID represents GraphQL's "ID" type. A custom type may be used instead.
type ID string

func (_ ID) ImplementsGraphQLType(name string) bool {
return name == "ID"
}

func (id *ID) UnmarshalGraphQL(input interface{}) error {
switch input := input.(type) {
case string:
*id = ID(input)
return nil
default:
return fmt.Errorf("wrong type")
}
}

func (id ID) MarshalJSON() ([]byte, error) {
return strconv.AppendQuote(nil, string(id)), nil
}

// ParseSchema parses a GraphQL schema and attaches the given root resolver. It returns an error if
// the Go type signature of the resolvers does not match the schema. If nil is passed as the
// resolver, then the schema can not be executed, but it may be inspected (e.g. with ToJSON).
Expand Down
30 changes: 30 additions & 0 deletions id.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package graphql

import (
"errors"
"strconv"
)

// ID represents GraphQL's "ID" scalar type. A custom type may be used instead.
type ID string

func (_ ID) ImplementsGraphQLType(name string) bool {
return name == "ID"
}

func (id *ID) UnmarshalGraphQL(input interface{}) error {
var err error
switch input := input.(type) {
case string:
*id = ID(input)
case int32:
*id = ID(strconv.Itoa(int(input)))
default:
err = errors.New("wrong type")
}
return err
}

func (id ID) MarshalJSON() ([]byte, error) {
return strconv.AppendQuote(nil, string(id)), nil
}

0 comments on commit d8c5743

Please sign in to comment.