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?
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With