GraphQL-变量未由操作定义 [英] GraphQL - variable not defined by operation

查看:222
本文介绍了GraphQL-变量未由操作定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的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
}

但是我只收到错误消息:Variable "$statusId" is not defined by operation "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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆