【问题标题】:GraphQL - variable not defined by operationGraphQL - 未由操作定义的变量
【发布时间】:2019-06-08 13:46:34
【问题描述】:

我的 GraphQL 架构定义为:

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 root resolver 方法。此查询如下所示:

query getEntityUsers($entityId: Int!, $statusId: Int) {
        users: getEntityUsers(entityId: $entityId, statusId: $statusId) {
            ...
        }
    }

.. 使用变量:

{
    entityId: 1,
    statusId: 2
}

有没有办法让我通过statusId 使其他方式工作?现在查询看起来像这样:

query getEntity($id: Int!) {
        entity: getEntity(id: $id) {
            ...
            users (statusId: 2) {
                ... 
            }
        }
    }

这显然适用于变量:

{
    id: 1
}

但是,如果我想使用第二种方法并更改statusId,该怎么办?如果没有在根解析器上定义statusId,是否还有传递?

我已经尝试过查询:

query getEntity($id: Int!) {
        entity: getEntity(id: $id) {
            ...
            users (statusId: $statusId) {
                ... 
            }
        }
    }

.. 使用变量:

{
    id: 1,
    statusId: 2
}

但我只是得到错误:Variable "$statusId" is not defined by operation "getEntity". 无论如何要这样做吗?

【问题讨论】:

    标签: graphql apollo-client


    【解决方案1】:

    每个操作(查询或突变)都必须明确定义您在该操作中使用的任何变量。因此,如果您有一个名为 $statusId 的变量,则必须将该变量的类型指定为操作定义的一部分:

    query getEntity($id: Int!, $statusId: Int) {
      # your selection set here
    }
    

    这些变量在查询中的使用位置(无论是在根级别还是其他地方)无关紧要——它们必须始终定义为操作定义的一部分。

    【讨论】:

    • 你能在这里扩展Int! vs Int吗?
    • @ElijahLynn 见here
    • @ElijahLynn Int 表示它可以为 null 但 Int!它不能传递空值
    猜你喜欢
    • 2021-04-17
    • 2018-11-21
    • 2019-06-15
    • 2017-03-18
    • 2020-11-06
    • 1970-01-01
    • 2018-11-23
    相关资源
    最近更新 更多