File: example_scalar_map_test.go

package info (click to toggle)
golang-github-graph-gophers-graphql-go 1.7.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,452 kB
  • sloc: sh: 373; javascript: 21; makefile: 5
file content (79 lines) | stat: -rw-r--r-- 1,169 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package graphql_test

import (
	"context"
	"encoding/json"
	"fmt"
	"os"

	"github.com/graph-gophers/graphql-go"
)

type Map map[string]interface{}

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

func (m *Map) UnmarshalGraphQL(input interface{}) error {
	val, ok := input.(map[string]interface{})
	if !ok {
		return fmt.Errorf("wrong type")
	}
	*m = val
	return nil
}

type Args struct {
	Name string
	Data Map
}

type mutation struct{}

func (*mutation) Hello(args Args) string {
	fmt.Println(args)
	return "Args accepted!"
}

func Example_customScalarMap() {
	s := `
		scalar Map
	
		type Query {}
		
		type Mutation {
			hello(
				name: String!
				data: Map!
			): String!
		}
	`
	schema := graphql.MustParseSchema(s, &mutation{})

	query := `
	  mutation {
		hello(name: "GraphQL", data: {
			num: 5,
			code: "example"
		})
	  }
	`

	res := schema.Exec(context.Background(), query, "", nil)

	enc := json.NewEncoder(os.Stdout)
	enc.SetIndent("", "  ")
	err := enc.Encode(res)
	if err != nil {
		panic(err)
	}

	// output:
	// {GraphQL map[code:example num:5]}
	// {
	//   "data": {
	//     "hello": "Args accepted!"
	//   }
	// }
}