首页 > 解决方案 > GraphQL - 未由操作定义的变量

问题描述

我的 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根解析器方法。此查询如下所示:

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".有没有办法做到这一点?

标签: graphqlapollo-client

解决方案


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

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

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


推荐阅读