Search code examples
graphqlapollographql-tag

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


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?


Solution

  • 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"