Skip to content

Commit

Permalink
update example todo add directive with location QUERY and MUTATION
Browse files Browse the repository at this point in the history
  • Loading branch information
asamusev committed Jun 14, 2019
1 parent 3eec887 commit 32462d0
Show file tree
Hide file tree
Showing 3 changed files with 120 additions and 4 deletions.
98 changes: 96 additions & 2 deletions example/todo/generated.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

14 changes: 12 additions & 2 deletions example/todo/todo.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,20 @@ import (
var you = &User{ID: 1, Name: "You"}
var them = &User{ID: 2, Name: "Them"}

func getUserId(ctx context.Context) int {
if id, ok := ctx.Value("userId").(int); ok {
return id
}
return you.ID
}

func New() Config {
c := Config{
Resolvers: &resolvers{
todos: []*Todo{
{ID: 1, Text: "A todo not to forget", Done: false, owner: you},
{ID: 2, Text: "This is the most important", Done: false, owner: you},
{ID: 3, Text: "Somebody else's todo", Done: true, owner: them},
{ID: 3, Text: "Somebody else's todo", Done: false, owner: them},
{ID: 4, Text: "Please do this or else", Done: false, owner: you},
},
lastID: 4,
Expand All @@ -38,13 +45,16 @@ func New() Config {
return nil, fmt.Errorf("obj cant be owned")
}

if ownable.Owner().ID != you.ID {
if ownable.Owner().ID != getUserId(ctx) {
return nil, fmt.Errorf("you dont own that")
}
}

return next(ctx)
}
c.Directives.User = func(ctx context.Context, obj interface{}, next graphql.Resolver, id int) (interface{}, error) {
return next(context.WithValue(ctx, "userId", id))
}
return c
}

Expand Down
12 changes: 12 additions & 0 deletions example/todo/todo_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,18 @@ func TestTodo(t *testing.T) {
require.Equal(t, "Very important", resp.UpdateTodo.Text)
})

t.Run("update the todo status by user id", func(t *testing.T) {
var resp struct {
UpdateTodo struct {
Text string
Done bool
}
}
c.MustPost(`mutation @user(id:2){ updateTodo(id: 3, changes:{done:true}) { text, done } }`, &resp)

require.Equal(t, "Somebody else's todo", resp.UpdateTodo.Text)
})

t.Run("select with alias", func(t *testing.T) {
var resp struct {
A struct{ Text string }
Expand Down

0 comments on commit 32462d0

Please sign in to comment.