0
votes

Hi there Golang experts,

  • I am using the Machinebox "github.com/machinebox/graphql" library in golang as client for my GraphQL server.

  • Mutations with single layer JSON variables work just fine

  • I am, however, at a loss as to how to pass a nested JSON as a variable

  • With a single layer JSON I simply create a map[string]string type and pass into the Var method. This in turn populates my graphql $data variable

  • The machinebox (graphql.Request).Var method takes an empty interface{} as value so the map[string]string works fine. But embedded json simply throws an error.

code:

func Mutate(data map[string]string, mutation string) interface{} {
    client := GQLClient()

    graphqlRequest := graphql.NewRequest(mutation)
    graphqlRequest.Var("data", data)

    var graphqlResponse interface{}
    if err := client.Run(context.Background(), graphqlRequest, &graphqlResponse); err != nil {
        panic(err)
    }

    return graphqlResponse
}

Mutation:

    mutation createWfLog($data: WfLogCreateInput)
        {
        createWfLog (data: $data){
            taskGUID {
                id
                status
                notes
            }
            event
            log
            createdBy
            }
        }
    

data variable shape:

{
  "data": {
    "event": "Task Create",
    "taskGUID": {
      "connect": {"id": "606f46cdbbe767001a3b4707"}
    },
    "log": "my log and information",
    "createdBy": "calvin cheng"
  }
}

As mentioned, the embedded json (value of taskGUID) presents the problem. If value was simple string type, it's not an issue.

  • Have tried using a struct to define every nesting, passed in struct.
  • Have tried unmarshaling a struct to json. Same error.

Any help appreciated

Calvin

1
How did you create the struct? Were all fields exported, as in did all struct field names start with a uppercase letter? You can use a tool like this to generate struct definitions. - xarantolus
Yes, all fields exported with caps. Nested fields had their own structs defined as well. It's interesting, I wonder if the (graphql.Request).Var(key, value) actually supports a nested map. For instance, if you were to use gin to respond to an endpoint request using c.JSON("200", response) - automagically converts your nested map response to json. Also @xarantolus, thanks for the tool link! that is so cool! - Calvin Cheng

1 Answers

1
votes

I have figured it out... and it is a case of my noobness with Golang.

I didn't need to do all this conversion of data or any such crazy type conversions. For some reason I got in my head everything HAD to be a map for the machinebox Var(key, value) to work

thanks to xarantolus's referenced site I was able to construct a proper strut. I populated the strut with my variable data (which was a nested json) and the mutation ran perfectly!

thanks!