Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 832
Vladyslav Zavalykhatko Avatar asked Oct 11 '19 08:10

Vladyslav Zavalykhatko


1 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
like image 166
Daniel Rearden Avatar answered Oct 04 '22 16:10

Daniel Rearden