Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

RequestedForContaining #10

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions requested_fields.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,3 +31,27 @@ func RequestedForAt(ctx context.Context, resolver interface{}, pathToAppend stri

return tree[pathTree]
}

// RequestedForContaining returns all requested fields for
//some path from a reference Resolver.
func RequestedForContaining(ctx context.Context, resolverString string) []string {
tree := ctx.Value(ContextKey).(map[string][]string)

var src = make(map[string]interface{})
for key, value := range tree {
if strings.Contains(key, resolverString) {
for _, val := range value {
src[val] = nil
}
}
}

var i = 0
var srcList = make([]string, len(src))
for k := range src {
srcList[i] = k
i = i + 1
}

return srcList
}
36 changes: 35 additions & 1 deletion requested_fields_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@ package fields

import (
"context"
"github.com/stretchr/testify/assert"
"sort"
"testing"

"github.com/stretchr/testify/assert"
)

var graphql_query_products string = `
Expand Down Expand Up @@ -86,3 +88,35 @@ func TestRequestedFieldsForUser(t *testing.T) {

assert.Equal(t, expected_fields, requested_fields)
}

var graphql_query_user_nested string = `
{
user(id: 3) {
id
name
user {
id
age
height
}
}
}
`

func TestRequestedFieldsForContainingUser(t *testing.T) {
query_resolver := &QueryResolver{}

user_resolver := &UserResolver{}
user_resolver.Field.SetParent(query_resolver)

ctx := context.WithValue(context.Background(),
ContextKey, BuildTree(graphql_query_user_nested, Variables{}))

expected_fields := []string{"id", "name", "age", "height", "user"}
requested_fields := RequestedForContaining(ctx, "user")

sort.Slice(expected_fields, func(i, j int) bool { return expected_fields[i] < expected_fields[j] })
sort.Slice(requested_fields, func(i, j int) bool { return requested_fields[i] < requested_fields[j] })

assert.Equal(t, expected_fields, requested_fields)
}