forked from samsarahq/thunder
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
105 lines (83 loc) · 2.16 KB
/
main.go
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
package main
import (
"context"
"net/http"
"github.com/samsarahq/thunder/graphql"
"github.com/samsarahq/thunder/graphql/graphiql"
"github.com/samsarahq/thunder/graphql/introspection"
"github.com/samsarahq/thunder/graphql/schemabuilder"
)
type Server struct {
}
type RoleType int32
type User struct {
Id int
FirstName string
LastName string
Role RoleType
}
func (s *Server) registerUser(schema *schemabuilder.Schema) {
object := schema.Object("User", User{})
object.Key("Id")
object.FieldFunc("fullName", func(u *User) string {
return u.FirstName + " " + u.LastName
})
}
type Args struct {
Role *RoleType
}
func (s *Server) registerQuery(schema *schemabuilder.Schema) {
object := schema.Query()
var tmp RoleType
schema.Enum(tmp, map[string]RoleType{
"user": RoleType(1),
"manager": RoleType(2),
"administrator": RoleType(3),
})
userListRet := func(ctx context.Context, args Args) ([]*User, error) {
return []*User{
{
Id: 1,
FirstName: "Bob",
LastName: "Johnson",
Role: RoleType(1),
},
{
Id: 2,
FirstName: "Chloe",
LastName: "Kim",
Role: RoleType(1),
},
}, nil
}
object.FieldFunc("users", userListRet)
object.PaginateFieldFunc("usersConnection", userListRet)
}
func (s *Server) registerMutation(schema *schemabuilder.Schema) {
object := schema.Mutation()
object.FieldFunc("echo", func(ctx context.Context, args struct{ Text string }) (string, error) {
return args.Text, nil
})
object.FieldFunc("echoEnum", func(ctx context.Context, args struct {
EnumField RoleType
}) (RoleType, error) {
return args.EnumField, nil
})
}
func (s *Server) Schema() *graphql.Schema {
schema := schemabuilder.NewSchema()
s.registerUser(schema)
s.registerQuery(schema)
s.registerMutation(schema)
return schema.MustBuild()
}
func main() {
server := &Server{}
graphqlSchema := server.Schema()
introspection.AddIntrospectionToSchema(graphqlSchema)
http.Handle("/graphql", graphql.Handler(graphqlSchema))
http.Handle("/graphiql/", http.StripPrefix("/graphiql/", graphiql.Handler()))
if err := http.ListenAndServe(":3030", nil); err != nil {
panic(err)
}
}