-
Notifications
You must be signed in to change notification settings - Fork 121
/
Copy pathserver.go
257 lines (217 loc) · 5.97 KB
/
server.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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
package server
import (
"context"
"fmt"
"net/http"
"net/http/httptest"
"strconv"
"time"
"github.com/99designs/gqlgen/graphql"
"github.com/99designs/gqlgen/graphql/handler"
"github.com/99designs/gqlgen/graphql/handler/transport"
)
func strptr(v string) *string { return &v }
func intptr(v int) *int { return &v }
var users = []*User{
{
ID: "1", Name: "Yours Truly", LuckyNumber: intptr(17),
Birthdate: strptr("2025-01-01"),
Hair: &Hair{Color: strptr("Black")},
GreatScalar: strptr("cool value"),
},
{ID: "2", Name: "Raven", LuckyNumber: intptr(-1), Hair: nil, GreatScalar: strptr("cool value")},
}
func init() {
users[0].Friends = []*User{users[1]} // (obviously a lie, but)
users[1].Friends = users // try to crash the system
}
var animals = []*Animal{
{
ID: "3", Name: "Fido", Species: SpeciesDog, Owner: userByID("1"),
Hair: &BeingsHair{HasHair: true},
},
{
ID: "4", Name: "Old One", Species: SpeciesCoelacanth, Owner: nil,
Hair: &BeingsHair{HasHair: false},
},
}
func userByID(id string) *User {
for _, user := range users {
if id == user.ID {
return user
}
}
return nil
}
func usersByBirthdates(dates []string) []*User {
var retval []*User
for _, date := range dates {
for _, user := range users {
if user.Birthdate != nil && *user.Birthdate == date {
retval = append(retval, user)
}
}
}
return retval
}
func beingByID(id string) Being {
for _, user := range users {
if id == user.ID {
return user
}
}
for _, animal := range animals {
if id == animal.ID {
return animal
}
}
return nil
}
func getNewID() string {
maxID := 0
for _, user := range users {
intID, _ := strconv.Atoi(user.ID)
if intID > maxID {
maxID = intID
}
}
for _, animal := range animals {
intID, _ := strconv.Atoi(animal.ID)
if intID > maxID {
maxID = intID
}
}
newID := maxID + 1
return strconv.Itoa(newID)
}
func (r *queryResolver) Me(ctx context.Context) (*User, error) {
return userByID("1"), nil
}
func (r *queryResolver) User(ctx context.Context, id *string) (*User, error) {
if id == nil {
return userByID("1"), nil
}
return userByID(*id), nil
}
func (r *queryResolver) Being(ctx context.Context, id string) (Being, error) {
return beingByID(id), nil
}
func (r *queryResolver) Beings(ctx context.Context, ids []string) ([]Being, error) {
ret := make([]Being, len(ids))
for i, id := range ids {
ret[i] = beingByID(id)
}
return ret, nil
}
func (r *queryResolver) LotteryWinner(ctx context.Context, number int) (Lucky, error) {
for _, user := range users {
if user.LuckyNumber != nil && *user.LuckyNumber == number {
return user, nil
}
}
return nil, nil
}
func (r *queryResolver) UsersBornOn(ctx context.Context, date string) ([]*User, error) {
return usersByBirthdates([]string{date}), nil
}
func (r *queryResolver) UsersBornOnDates(ctx context.Context, dates []string) ([]*User, error) {
return usersByBirthdates(dates), nil
}
func (r *queryResolver) UserSearch(ctx context.Context, birthdate *string, id *string) ([]*User, error) {
switch {
case birthdate == nil && id != nil:
return []*User{userByID(*id)}, nil
case birthdate != nil && id == nil:
return usersByBirthdates([]string{*birthdate}), nil
default:
return nil, fmt.Errorf("need exactly one of birthdate or id")
}
}
func (r *queryResolver) Fail(ctx context.Context) (*bool, error) {
f := true
return &f, fmt.Errorf("oh no")
}
func (m mutationResolver) CreateUser(ctx context.Context, input NewUser) (*User, error) {
newUser := User{ID: getNewID(), Name: input.Name, Friends: []*User{}}
users = append(users, &newUser)
return &newUser, nil
}
func (s *subscriptionResolver) Count(ctx context.Context) (<-chan int, error) {
respChan := make(chan int, 1)
go func(respChan chan int) {
defer close(respChan)
counter := 0
for {
if counter == 10 {
return
}
respChan <- counter
counter++
time.Sleep(100 * time.Millisecond)
}
}(respChan)
return respChan, nil
}
func (s *subscriptionResolver) CountAuthorized(ctx context.Context) (<-chan int, error) {
if getAuthToken(ctx) != "authorized-user-token" {
return nil, fmt.Errorf("unauthorized")
}
return s.Count(ctx)
}
const AuthKey = "authToken"
type (
authTokenCtxKey struct{}
)
func withAuthToken(ctx context.Context, token string) context.Context {
return context.WithValue(ctx, authTokenCtxKey{}, token)
}
func getAuthToken(ctx context.Context) string {
if tkn, ok := ctx.Value(authTokenCtxKey{}).(string); ok {
return tkn
}
return ""
}
func authHeaderMiddleware(handler http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
token := r.Header.Get(AuthKey)
if token != "" {
ctx = withAuthToken(ctx, token)
}
r = r.WithContext(ctx)
handler.ServeHTTP(w, r)
})
}
func RunServer() *httptest.Server {
gqlgenServer := handler.New(NewExecutableSchema(Config{Resolvers: &resolver{}}))
gqlgenServer.AddTransport(transport.POST{})
gqlgenServer.AddTransport(transport.GET{})
gqlgenServer.AddTransport(transport.Websocket{
InitFunc: func(ctx context.Context, initPayload transport.InitPayload) (context.Context, *transport.InitPayload, error) {
if authToken, ok := initPayload[AuthKey].(string); ok && authToken != "" {
ctx = withAuthToken(ctx, authToken)
}
return ctx, &initPayload, nil
},
})
gqlgenServer.AroundResponses(func(ctx context.Context, next graphql.ResponseHandler) *graphql.Response {
graphql.RegisterExtension(ctx, "foobar", "test")
return next(ctx)
})
server := authHeaderMiddleware(gqlgenServer)
return httptest.NewServer(server)
}
type (
resolver struct{}
queryResolver struct{}
mutationResolver struct{}
subscriptionResolver struct{}
)
func (r *resolver) Mutation() MutationResolver {
return &mutationResolver{}
}
func (r *resolver) Query() QueryResolver { return &queryResolver{} }
func (r *resolver) Subscription() SubscriptionResolver {
return &subscriptionResolver{}
}
//go:generate go run github.com/99designs/[email protected]