forked from 99designs/gqlgen
-
Notifications
You must be signed in to change notification settings - Fork 0
/
todo.go
126 lines (100 loc) · 2.5 KB
/
todo.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
//go:generate gorunpkg github.com/99designs/gqlgen --out generated.go
package todo
import (
"context"
"errors"
"time"
graphql "github.com/99designs/gqlgen/graphql"
"github.com/mitchellh/mapstructure"
)
func New() Config {
c := Config{
Resolvers: &resolvers{
todos: []Todo{
{ID: 1, Text: "A todo not to forget", Done: false},
{ID: 2, Text: "This is the most important", Done: false},
{ID: 3, Text: "Please do this or else", Done: false},
},
lastID: 3,
},
}
c.Directives.HasRole = func(ctx context.Context, next graphql.Resolver, role Role) (interface{}, error) {
rctx := graphql.GetResolverContext(ctx)
idVal := rctx.Field.Arguments.ForName("id").Value
id, _ := idVal.Value(make(map[string]interface{}))
if id.(int64) == 1 && role == RoleAdmin {
return nil, nil
}
return next(ctx)
}
return c
}
type resolvers struct {
todos []Todo
lastID int
}
func (r *resolvers) MyQuery() MyQueryResolver {
return (*QueryResolver)(r)
}
func (r *resolvers) MyMutation() MyMutationResolver {
return (*MutationResolver)(r)
}
type QueryResolver resolvers
func (r *QueryResolver) Todo(ctx context.Context, id int) (*Todo, error) {
time.Sleep(220 * time.Millisecond)
if id == 666 {
panic("critical failure")
}
for _, todo := range r.todos {
if todo.ID == id {
return &todo, nil
}
}
return nil, errors.New("not found")
}
func (r *QueryResolver) LastTodo(ctx context.Context) (*Todo, error) {
if len(r.todos) == 0 {
return nil, errors.New("not found")
}
return &r.todos[len(r.todos)-1], nil
}
func (r *QueryResolver) Todos(ctx context.Context) ([]Todo, error) {
return r.todos, nil
}
func (r *QueryResolver) AuthenticatedTodo(ctx context.Context, id int) (*Todo, error) {
return r.Todo(ctx, id)
}
type MutationResolver resolvers
func (r *MutationResolver) CreateTodo(ctx context.Context, todo TodoInput) (Todo, error) {
newID := r.id()
newTodo := Todo{
ID: newID,
Text: todo.Text,
}
if todo.Done != nil {
newTodo.Done = *todo.Done
}
r.todos = append(r.todos, newTodo)
return newTodo, nil
}
func (r *MutationResolver) UpdateTodo(ctx context.Context, id int, changes map[string]interface{}) (*Todo, error) {
var affectedTodo *Todo
for i := 0; i < len(r.todos); i++ {
if r.todos[i].ID == id {
affectedTodo = &r.todos[i]
break
}
}
if affectedTodo == nil {
return nil, nil
}
err := mapstructure.Decode(changes, affectedTodo)
if err != nil {
panic(err)
}
return affectedTodo, nil
}
func (r *MutationResolver) id() int {
r.lastID++
return r.lastID
}