How to get the name of a query from a `gql` object?

Viewed 2826

I use gql from graphql-tag. Let's say I have a gql object defined like this:

const QUERY_ACCOUNT_INFO = gql`
  query AccountInfo {
    viewer {
      lastname
      firstname
      email
      phone
      id
    }
  }
`

There must be a way to get AccountInfo from it. How can I do it?

2 Answers

What's returned by gql is a DocumentNode object. A GraphQL document could include multiple definitions, but assuming it only has the one and it's an operation, you can just do:

const operation = doc.definitions[0]
const operationName = operation && operation.name

If we allow there may be fragments, we probably want to do:

const operation = doc.definitions.find((def) => def.kind === 'OperationDefinition')
const operationName = operation && operation.name

Keep in mind it's technically possible for multiple operations to exist in the same document, but if you're running this client-side against your own code that fact may be irrelevant.

The core library also provides a utility function:

const { getOperationAST } = require('graphql')
const operation = getOperationAST(doc)
const operationName = operation && operation.name

If you are using Apollo there is also the explicit getOperationName which seems to be rather undocumented but has worked for all my usecases.

import { getOperationName } from "@apollo/client/utilities";

export const AdminListItemsDocument = gql`
  query AdminListItems(
    $first: Int
    $after: String
    $before: String
    $last: Int
  ) {
    items(
      first: $first
      after: $after
      before: $before
      last: $last
    ) {
      nodes {
        id
        name
      }
      totalCount
      pageInfo {
        hasPreviousPage
        hasNextPage
        startCursor
        endCursor
      }
    }
  }
`;

getOperationName(AdminListBlockLanguagesDocument); // => "AdminListItems"
Related