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

Allow [][2]interface{} (ordered map) along with struct in query and mutation #80 #81

Open
wants to merge 8 commits into
base: main
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
38 changes: 38 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -276,6 +276,44 @@ fmt.Printf("Created a %v star review: %v\n", m.CreateReview.Stars, m.CreateRevie
// Created a 5 star review: This is a great movie!
```

### Multiple mutations with ordered map

You might need to make multiple mutations in single query. It's not very convenient with structs
so you can use ordered map `[][2]interface{}` instead.

For example, to make the following GraphQL mutation:

```GraphQL
mutation($login1: String!, $login2: String!, $login3: String!) {
createUser(login: $login1) { login }
createUser(login: $login2) { login }
createUser(login: $login3) { login }
}
variables {
"login1": "grihabor",
"login2": "diman",
"login3": "indigo"
}
```

You can define:

```Go
type CreateUser struct {
Login graphql.String
}
m := [][2]interface{}{
{"createUser(login: $login1)", &CreateUser{}},
{"createUser(login: $login2)", &CreateUser{}},
{"createUser(login: $login3)", &CreateUser{}},
}
variables := map[string]interface{}{
"login1": graphql.String("grihabor"),
"login2": graphql.String("diman"),
"login3": graphql.String("indigo"),
}
```

Directories
-----------

Expand Down
9 changes: 9 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
module github.com/shurcooL/graphql

go 1.16

require (
github.com/graph-gophers/graphql-go v1.2.0
github.com/stretchr/testify v1.7.0 // indirect
golang.org/x/net v0.0.0-20211109214657-ef0fda0de508
)
21 changes: 21 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/graph-gophers/graphql-go v1.2.0 h1:j3tCG0UcE+3f84OAw/4/6YQKyTr+r0yuUKtnxiu5OH4=
github.com/graph-gophers/graphql-go v1.2.0/go.mod h1:9CQHMSxwO4MprSdzoIEobiHpoLtHm77vfxsvsIN5Vuc=
github.com/opentracing/opentracing-go v1.1.0 h1:pWlfV3Bxv7k65HYwkikxat0+s3pV4bsqf19k25Ur8rU=
github.com/opentracing/opentracing-go v1.1.0/go.mod h1:UkNAQd3GIcIGf0SeVgPpRdFStlNbqXla1AfSYxPUl2o=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
golang.org/x/net v0.0.0-20211109214657-ef0fda0de508 h1:v3NKo+t/Kc3EASxaKZ82lwK6mCf4ZeObQBduYFZHo7c=
golang.org/x/net v0.0.0-20211109214657-ef0fda0de508/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
170 changes: 146 additions & 24 deletions internal/jsonutil/graphql.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,17 @@ type decoder struct {
// The reason there's more than one stack is because we might be unmarshaling
// a single JSON value into multiple GraphQL fragments or embedded structs, so
// we keep track of them all.
vs [][]reflect.Value
vs []stack
}

type stack []reflect.Value

func (s stack) Top() reflect.Value {
return s[len(s)-1]
}

func (s stack) Pop() stack {
return s[:len(s)-1]
}

// Decode decodes a single JSON value from d.tokenizer into v.
Expand All @@ -62,7 +72,7 @@ func (d *decoder) Decode(v interface{}) error {
if rv.Kind() != reflect.Ptr {
return fmt.Errorf("cannot decode into non-pointer %T", v)
}
d.vs = [][]reflect.Value{{rv.Elem()}}
d.vs = []stack{{rv.Elem()}}
return d.decode()
}

Expand All @@ -88,16 +98,22 @@ func (d *decoder) decode() error {
}
someFieldExist := false
for i := range d.vs {
v := d.vs[i][len(d.vs[i])-1]
if v.Kind() == reflect.Ptr {
v := d.vs[i].Top()
if v.Kind() == reflect.Ptr || v.Kind() == reflect.Interface {
v = v.Elem()
}
var f reflect.Value
if v.Kind() == reflect.Struct {
switch v.Kind() {
case reflect.Struct:
f = fieldByGraphQLName(v, key)
if f.IsValid() {
someFieldExist = true
}
case reflect.Slice:
f = orderedMapValueByGraphQLName(v, key)
if f.IsValid() {
someFieldExist = true
}
}
d.vs[i] = append(d.vs[i], f)
}
Expand All @@ -118,13 +134,15 @@ func (d *decoder) decode() error {
case d.state() == '[' && tok != json.Delim(']'):
someSliceExist := false
for i := range d.vs {
v := d.vs[i][len(d.vs[i])-1]
v := d.vs[i].Top()
if v.Kind() == reflect.Ptr {
v = v.Elem()
}
var f reflect.Value
if v.Kind() == reflect.Slice {
v.Set(reflect.Append(v, reflect.Zero(v.Type().Elem()))) // v = append(v, T).
// we want to append the template item copy
// so that all the inner structure gets preserved
v.Set(reflect.Append(v, copyTemplate(v.Index(0)))) // v = append(v, T).
f = v.Index(v.Len() - 1)
someSliceExist = true
}
Expand All @@ -140,7 +158,7 @@ func (d *decoder) decode() error {
// Value.

for i := range d.vs {
v := d.vs[i][len(d.vs[i])-1]
v := d.vs[i].Top()
if !v.IsValid() {
continue
}
Expand All @@ -160,7 +178,7 @@ func (d *decoder) decode() error {

frontier := make([]reflect.Value, len(d.vs)) // Places to look for GraphQL fragments/embedded structs.
for i := range d.vs {
v := d.vs[i][len(d.vs[i])-1]
v := d.vs[i].Top()
frontier[i] = v
// TODO: Do this recursively or not? Add a test case if needed.
if v.Kind() == reflect.Ptr && v.IsNil() {
Expand All @@ -175,14 +193,23 @@ func (d *decoder) decode() error {
if v.Kind() == reflect.Ptr {
v = v.Elem()
}
if v.Kind() != reflect.Struct {
continue
}
for i := 0; i < v.NumField(); i++ {
if isGraphQLFragment(v.Type().Field(i)) || v.Type().Field(i).Anonymous {
// Add GraphQL fragment or embedded struct.
d.vs = append(d.vs, []reflect.Value{v.Field(i)})
frontier = append(frontier, v.Field(i))
if v.Kind() == reflect.Struct {
for i := 0; i < v.NumField(); i++ {
if isGraphQLFragment(v.Type().Field(i)) || v.Type().Field(i).Anonymous {
// Add GraphQL fragment or embedded struct.
d.vs = append(d.vs, []reflect.Value{v.Field(i)})
frontier = append(frontier, v.Field(i))
}
}
} else if isOrderedMap(v) {
for i := 0; i < v.Len(); i++ {
pair := v.Index(i)
key, val := pair.Index(0), pair.Index(1)
if keyForGraphQLFragment(key.Interface().(string)) {
// Add GraphQL fragment or embedded struct.
d.vs = append(d.vs, []reflect.Value{val})
frontier = append(frontier, val)
}
}
}
}
Expand All @@ -192,7 +219,7 @@ func (d *decoder) decode() error {
d.pushState(tok)

for i := range d.vs {
v := d.vs[i][len(d.vs[i])-1]
v := d.vs[i].Top()
// TODO: Confirm this is needed, write a test case.
//if v.Kind() == reflect.Ptr && v.IsNil() {
// v.Set(reflect.New(v.Type().Elem())) // v = new(T).
Expand All @@ -205,10 +232,28 @@ func (d *decoder) decode() error {
if v.Kind() != reflect.Slice {
continue
}
v.Set(reflect.MakeSlice(v.Type(), 0, 0)) // v = make(T, 0, 0).
newSlice := reflect.MakeSlice(v.Type(), 0, 0) // v = make(T, 0, 0).
switch v.Len() {
case 0:
// if there is no template we need to create one so that we can
// handle both cases (with or without a template) in the same way
newSlice = reflect.Append(newSlice, reflect.Zero(v.Type().Elem()))
case 1:
// if there is a template, we need to keep it at index 0
newSlice = reflect.Append(newSlice, v.Index(0))
case 2:
msg := fmt.Sprintf("template slice can only have 1 item")
panic(msg)
}
v.Set(newSlice)
}
case '}', ']':
// End of object or array.
case '}':
// End of object.
d.popAllVs()
d.popState()
case ']':
// End of array.
d.popLeftArrayTemplates()
d.popAllVs()
d.popState()
default:
Expand All @@ -221,6 +266,38 @@ func (d *decoder) decode() error {
return nil
}

func copyTemplate(template reflect.Value) reflect.Value {
if isOrderedMap(template) {
// copy slice if it's actually an ordered map
return copyOrderedMap(template)
}
if template.Kind() == reflect.Map {
msg := fmt.Sprintf("unsupported template type `%v`, use [][2]interface{} for ordered map instead", template.Type())
panic(msg)
}
// don't need to copy regular slice
return template
}

func isOrderedMap(v reflect.Value) bool {
if !v.IsValid() {
return false
}
t := v.Type()
return t.Kind() == reflect.Slice &&
t.Elem().Kind() == reflect.Array &&
t.Elem().Len() == 2
}

func copyOrderedMap(m reflect.Value) reflect.Value {
newMap := reflect.MakeSlice(m.Type(), 0, m.Len())
for i := 0; i < m.Len(); i++ {
pair := m.Index(i)
newMap = reflect.Append(newMap, pair)
}
return newMap
}

// pushState pushes a new parse state s onto the stack.
func (d *decoder) pushState(s json.Delim) {
d.parseState = append(d.parseState, s)
Expand All @@ -242,16 +319,26 @@ func (d *decoder) state() json.Delim {

// popAllVs pops from all d.vs stacks, keeping only non-empty ones.
func (d *decoder) popAllVs() {
var nonEmpty [][]reflect.Value
var nonEmpty []stack
for i := range d.vs {
d.vs[i] = d.vs[i][:len(d.vs[i])-1]
d.vs[i] = d.vs[i].Pop()
if len(d.vs[i]) > 0 {
nonEmpty = append(nonEmpty, d.vs[i])
}
}
d.vs = nonEmpty
}

// popLeftArrayTemplates pops left from last array items of all d.vs stacks.
func (d *decoder) popLeftArrayTemplates() {
for i := range d.vs {
v := d.vs[i].Top()
if v.IsValid() {
v.Set(v.Slice(1, v.Len()))
}
}
}

// fieldByGraphQLName returns an exported struct field of struct v
// that matches GraphQL name, or invalid reflect.Value if none found.
func fieldByGraphQLName(v reflect.Value, name string) reflect.Value {
Expand All @@ -267,6 +354,19 @@ func fieldByGraphQLName(v reflect.Value, name string) reflect.Value {
return reflect.Value{}
}

// orderedMapValueByGraphQLName takes [][2]string, interprets it as an ordered map
// and returns value for corresponding key, or invalid reflect.Value if none found.
func orderedMapValueByGraphQLName(v reflect.Value, name string) reflect.Value {
for i := 0; i < v.Len(); i++ {
pair := v.Index(i)
key := pair.Index(0).Interface().(string)
if keyHasGraphQLName(key, name) {
return pair.Index(1)
}
}
return reflect.Value{}
}

// hasGraphQLName reports whether struct field f has GraphQL name.
func hasGraphQLName(f reflect.StructField, name string) bool {
value, ok := f.Tag.Lookup("graphql")
Expand All @@ -275,6 +375,10 @@ func hasGraphQLName(f reflect.StructField, name string) bool {
//return caseconv.MixedCapsToLowerCamelCase(f.Name) == name
return strings.EqualFold(f.Name, name)
}
return keyHasGraphQLName(value, name)
}

func keyHasGraphQLName(value, name string) bool {
value = strings.TrimSpace(value) // TODO: Parse better.
if strings.HasPrefix(value, "...") {
// GraphQL fragment. It doesn't have a name.
Expand All @@ -295,6 +399,11 @@ func isGraphQLFragment(f reflect.StructField) bool {
if !ok {
return false
}
return keyForGraphQLFragment(value)
}

// isGraphQLFragment reports whether ordered map kv pair f is a GraphQL fragment.
func keyForGraphQLFragment(value string) bool {
value = strings.TrimSpace(value) // TODO: Parse better.
return strings.HasPrefix(value, "...")
}
Expand All @@ -307,5 +416,18 @@ func unmarshalValue(value json.Token, v reflect.Value) error {
if err != nil {
return err
}
return json.Unmarshal(b, v.Addr().Interface())
ty := v.Type()
if ty.Kind() == reflect.Interface {
if !v.Elem().IsValid() {
return json.Unmarshal(b, v.Addr().Interface())
}
ty = v.Elem().Type()
}
newVal := reflect.New(ty)
err = json.Unmarshal(b, newVal.Interface())
if err != nil {
return err
}
v.Set(newVal.Elem())
return nil
}
Loading