简体   繁体   中英

GraphQL - variable not defined by operation

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]
}

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) {
            ...
        }
    }

.. with the variables:

{
    entityId: 1,
    statusId: 2
}

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) {
                ... 
            }
        }
    }

This obviously works with the variables:

{
    id: 1
}

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?

I have tried the query:

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

.. with the variables:

{
    id: 1,
    statusId: 2
}

But I just get the error: Variable "$statusId" is not defined by operation "getEntity". Is there anyway to do this?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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