当我使用 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屋!