javascriptgraphqlgraphql-jsgraphql-tools

Graphql - How to get type (String, Int, ID etc..) of a selected field


I have the following graphql query

const GET_USER = gql`
    query user() {
        user {
            firstName
            lastName
        }
    }
`

I traverse through the query to find the type of the firstName & the lastName field using visit function provided by graphql

visit(GET_USER, {
    Field(node) {
      console.log(node)
    }
  }

it looks like the fields contain only the following information.

{
      kind: 'Field',
      alias: undefined,
      name: { kind: 'Name', value: 'firstName' },
      arguments: [],
      directives: [],
      selectionSet: undefined
},
{
      kind: 'Field',
      alias: undefined,
      name: { kind: 'Name', value: 'lastName' },
      arguments: [],
      directives: [],
      selectionSet: undefined
}

which doesn't tell me the type of firstName & lastName

I am expecting that I will probably have to make use of the related schema file to get the types of that query but I am not sure how to do that, if anyone can help me with that, that would be great.


Solution

  • Use Introspection

    Not sure what platform you're using but introspection is what you use to get information on a particular type.

    Introspection is the ability to query which resources are available in the current API schema.

    Example for User type:

    {
      __type(name: "User") {
         name
         kind
      }
    }
    

    Example Response:

    {
      "data": {
        "__type": {
          "name": "User",
          "kind": "OBJECT"
        }
      }
    }
    

    You can use introspection to drill into fields as well:

    {
      __type(name: "User") {
        name
        fields {
          name
          type {
            name
            kind
          }
        }
      }
    }
    

    Example Response:

    {
      "data": {
        "__type": {
          "name": "User",
          "fields": [
            {
              "name": "id",
              "type": {
                "name": null,
                "kind": "NON_NULL",
                "ofType": {
                  "name": "ID",
                  "kind": "SCALAR"
                }
              }
            },
            {
              "name": "name",
              "type": {
                "name": null,
                "kind": "NON_NULL",
                "ofType": {
                  "name": "String",
                  "kind": "SCALAR"
                }
              }
            }
          ]
        }
      }
    }