繁体   English   中英

GraphQL - 未由操作定义的变量

[英]GraphQL - variable not defined by operation

我的 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 如果它没有在根解析器上定义,是否有传递statusId的方法?

我试过查询:

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

.. 变量:

{
    id: 1,
    statusId: 2
}

但我只是收到错误: Variable "$statusId" is not defined by operation "getEntity". 有没有办法做到这一点?

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM