Search code examples
graphqlapollograndstack

Using ID in GraphQL parametrized query


I have the following schema:

type Post {
  id: ID!
  text: String
}

I am using autogenerated mutations from neo4j-graphql.js, so I have access to the following mutation:

UpdatePost(
id: ID!
text: String
): Post

The issue:

When I'm using the following query:

mutation update($id: String, $text: String) {
  UpdatePost(id: $id, text: $text) {
    id
    text
  }
}

With the following parameters:

{
  "id": "a19289b3-a191-46e2-9912-5a3d1b067cb2",
  "text": "text"
}

I get the following error:

{
  "error": {
    "errors": [
      {
        "message": "Variable \"$id\" of type \"String\" used in position expecting type \"ID!\".",
        "locations": [
          {
            "line": 1,
            "column": 17
          },
          {
            "line": 2,
            "column": 18
          }
        ],
        "extensions": {
          "code": "GRAPHQL_VALIDATION_FAILED"
        }
      }
    ]
  }
}

Is there a way to convert my string ID to the actual ID type? Or circumvent this error altogether?


Solution

  • The error you're seeing is related to the type of your variables as specified in your query's variable definitions. It has nothing to do with the values of the variables (which appear to be correct). Based on the error message, the type of your $id variable is String, not ID as shown in the query you pasted.

    Regardless, because the type of the id argument (where the $id variable is being used) is ID!, not ID, then your variable's type should also be ID!.

    The ! indicates a non-null (required) type. In other words, the id argument must always be provided and it cannot be given the value null. Any variable passed the argument must also be non-null. If the variable's type is ID instead of ID!, we're telling GraphQL the variable might be omitted or have a null value, which would be incompatible with the argument where it's being used.

    Note that the opposite is not true: if the argument's type was ID, then either an ID or ID! variable would be valid.