0
votes

In our project we use Apollo client to send queries to GraphQL. Strangely it converts the variables into object of objects.

let variables = [{myField: "myVal"}];
graphql.mutate("mutate myFunction($data:[MyInputType]){
    myFunction(myArg: $data){...blabla...}
}", variables);

When I run the mutation and check request headers, I see that my variables are converted into object of objects.

{"0": {"myField": "myVal"}}

Does this method force variables to be object by default? Is it possible to send array of objects as parameter using GraphQL?

1

1 Answers

1
votes

When executing a query, GraphQL expects variables to be an object where the key is the variable name and the value is the corresponding variable value. Every variable used within a document (the entire query you send) must be declared next to the operation definition for the document. For example, if you have a variable named firstName that was a String:

mutation SomeOperationName ($firstName: String) {
  # your mutation here
}

You can include any number of variables:

mutation SomeOperationName ($firstName: String, $lastName: String, points: Int)

Variables can also be lists:

mutation SomeOperationName ($names: [String], points: Int)

In all these cases, however, the value for variables you pass to mutate still needs to be an object:

{
  names: ['Bob', 'Susan'],
  points: 12,
}

In your example, you've only defined a single variable, data, that you've told GraphQL is a List of MyInputType. You can't pass in myField as a variable because you have not told GraphQL that variable exists. However, if myField is a field on MyInputType, then your variables just needs to look like this:

{
  data: [
    {
        myField: 'someValue'
    },
    {
        myField: 'someOtherValue'
    },
  ],
}