Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 207
jrkt Avatar asked Feb 03 '23 20:02

jrkt


1 Answers

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.

like image 98
Daniel Rearden Avatar answered Feb 19 '23 15:02

Daniel Rearden