GraphQL - 未由操作定义的变量 [英] GraphQL - variable not defined by operation
问题描述
我的 GraphQL 架构定义为:
My GraphQL schema is defined as:
type Query {
getEntity(id: Int!): Entity
getEntityUsers(entityId: Int!, statusId: Int): [User]
}
type Entity {
id: Int!
name: String!
email: String!
logo: String
createdAt: DateTime!
updatedAt: DateTime!
users(statusId: Int): [User]
}
如您所见,我有两种方法可以为 Entity
对象获取用户.目前适用于我的查询的是 getEntityUsers
根解析器方法.此查询如下所示:
As you can see I have two ways of getting users for an Entity
object. The one that is currently working for my query is the getEntityUsers
root resolver method. This query looks like this:
query getEntityUsers($entityId: Int!, $statusId: Int) {
users: getEntityUsers(entityId: $entityId, statusId: $statusId) {
...
}
}
.. 与变量:
{
entityId: 1,
statusId: 2
}
无论如何,是否可以通过允许我传入 statusId
来使另一种方式起作用?现在查询看起来像这样:
Is there anyway to make the other way work by allowing me to pass in the statusId
? Right now the query looks like this:
query getEntity($id: Int!) {
entity: getEntity(id: $id) {
...
users (statusId: 2) {
...
}
}
}
这显然适用于变量:
{
id: 1
}
但是,如果我想使用第二种方法并更改 statusId
怎么办?如果 statusId
没有在根解析器上定义,是否有任何方法可以传入?
But, what if I wanted to use this second method and change the statusId
? Is there anyway to pass in the statusId
if it's not defined on the root resolver?
我已经尝试过查询:
query getEntity($id: Int!) {
entity: getEntity(id: $id) {
...
users (statusId: $statusId) {
...
}
}
}
.. 与变量:
{
id: 1,
statusId: 2
}
但我刚刚收到错误消息:变量$statusId"不是由操作getEntity"定义的.
有没有办法做到这一点?
But I just get the error: Variable "$statusId" is not defined by operation "getEntity".
Is there anyway to do this?
推荐答案
每个操作(查询或变异)都必须明确定义您在该操作中使用的任何变量.因此,如果您有一个名为 $statusId
的变量,则必须将此变量的类型指定为操作定义的一部分:
Every operation (query or mutation) must explicitly define any variables you use inside that operation. So if you have a variable called $statusId
, the type for this variable must be specified as part of your operation definition:
query getEntity($id: Int!, $statusId: Int) {
# your selection set here
}
这些变量在您的查询中的使用位置(无论是在根级别还是其他地方)无关紧要——它们必须始终被定义为您的操作定义的一部分.
Where those variables are used within your query (whether at the root level, or elsewhere) is irrelevant -- they must always be defined as part of your operation definition.
这篇关于GraphQL - 未由操作定义的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!