当我使用Apollo时,对象数组转换为对象对象 [英] Array of objects convert into object of objects when I use Apollo
问题描述
在我们的项目中,我们使用Apollo客户端将查询发送到GraphQL.奇怪的是,它将变量转换为对象的对象.
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"}}
此方法是否默认将变量强制为对象?是否可以使用GraphQL将对象数组作为参数发送?
Does this method force variables to be object by default? Is it possible to send array of objects as parameter using GraphQL?
推荐答案
在执行查询时,GraphQL期望variables
是一个对象,其中键是变量名,值是相应的变量值.必须在文档的操作定义旁边声明文档中使用的每个变量(发送的整个查询).例如,如果您有一个名为firstName
的变量,该变量为String
:
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)
变量也可以是列表:
mutation SomeOperationName ($names: [String], points: Int)
在所有这些情况下,传递给mutate
的variables
的值仍需要是一个对象:
In all these cases, however, the value for variables
you pass to mutate
still needs to be an object:
{
names: ['Bob', 'Susan'],
points: 12,
}
在您的示例中,您仅定义了一个变量data
,您已将GraphQL称为MyInputType
的List
.您不能将myField
作为变量传递,因为您没有告诉GraphQL该变量存在.但是,如果myField
是MyInputType
上的字段,则您的variables
只需看起来像这样:
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'
},
],
}
这篇关于当我使用Apollo时,对象数组转换为对象对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!