Skip to content

Commit

Permalink
Merge pull request #686 from qhenkart/master
Browse files Browse the repository at this point in the history
Adds default custom scalar of interface{}
  • Loading branch information
vektah committed May 8, 2019
2 parents d1e8acd + bf2d07a commit 4e359aa
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 3 deletions.
1 change: 1 addition & 0 deletions codegen/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -365,6 +365,7 @@ func (c *Config) InjectBuiltins(s *ast.Schema) {
extraBuiltins := TypeMap{
"Time": {Model: StringList{"github.com/99designs/gqlgen/graphql.Time"}},
"Map": {Model: StringList{"github.com/99designs/gqlgen/graphql.Map"}},
"Any": {Model: StringList{"github.com/99designs/gqlgen/graphql.Any"}},
}

for typeName, entry := range extraBuiltins {
Expand Down
14 changes: 11 additions & 3 deletions docs/content/reference/scalars.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ menu: { main: { parent: 'reference' } }

## Built-in helpers

gqlgen ships with two built-in helpers for common custom scalar use-cases, `Time` and `Map`. Adding either of these to a schema will automatically add the marshalling behaviour to Go types.
gqlgen ships with three built-in helpers for common custom scalar use-cases, `Time`, `Any` and `Map`. Adding any of these to a schema will automatically add the marshalling behaviour to Go types.

### Time

Expand All @@ -25,6 +25,14 @@ scalar Map

Maps an arbitrary GraphQL value to a `map[string]{interface}` Go type.

### Any

```graphql
scalar Any
```

Maps an arbitrary GraphQL value to a `interface{}` Go type.

## Custom scalars with user defined types

For user defined types you can implement the graphql.Marshal and graphql.Unmarshal interfaces and they will be called.
Expand Down Expand Up @@ -75,7 +83,7 @@ models:

## Custom scalars with third party types

Sometimes you cant add methods to a type because its in another repo, part of the standard
Sometimes you cant add methods to a type because its in another repo, part of the standard
library (eg string or time.Time). To do this we can build an external marshaler:

```go
Expand All @@ -85,7 +93,7 @@ import (
"fmt"
"io"
"strings"

"github.com/99designs/gqlgen/graphql"
)

Expand Down
19 changes: 19 additions & 0 deletions graphql/any.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package graphql

import (
"encoding/json"
"io"
)

func MarshalAny(v interface{}) Marshaler {
return WriterFunc(func(w io.Writer) {
err := json.NewEncoder(w).Encode(v)
if err != nil {
panic(err)
}
})
}

func UnmarshalAny(v interface{}) (interface{}, error) {
return v, nil
}

0 comments on commit 4e359aa

Please sign in to comment.