问题描述
在我们的项目中,我们使用Apollo客户端将查询发送到GraphQl.奇怪的是,它将变量转换为对象的对象.
let variables = [{myField: "myVal"}]; graphql.mutate("mutate myFunction($data:[MyInputType]){ myFunction(myArg: $data){...blabla...} }", variables);
当我运行突变并检查请求标头时,我看到我的变量转换为对象的对象.
{"0": {"myField": "myVal"}}
此方法是否默认情况下将变量迫使变量为对象?是否可以使用GraphQl?
将对象数组作为参数发送数组推荐答案
执行查询时,GraphQl期望variables是一个对象,其中键是变量名称,该值是相应的变量值.文档中使用的每个变量(您发送的整个查询)必须在文档操作定义旁边声明.例如,如果您有一个名为firstName的变量,那就是String:
mutation SomeOperationName ($firstName: String) { # your mutation here }
您可以包括任意数量的变量:
mutation SomeOperationName ($firstName: String, $lastName: String, points: Int)
变量也可以是列表:
mutation SomeOperationName ($names: [String], points: Int)
在所有这些情况下,variables的值您传递给mutate仍然需要是一个对象:
{ names: ['Bob', 'Susan'], points: 12, }
在您的示例中,您只定义了一个变量,data您已经告诉GraphQl是MyInputType的List.您不能将myField作为变量传递,因为您尚未告诉GraphQl存在变量.但是,如果myField是MyInputType上的字段,那么您的variables只需看起来像这样:
{ data: [ { myField: 'someValue' }, { myField: 'someOtherValue' }, ], }
问题描述
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?
推荐答案
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' }, ], }