Why do you need graphql-tag with Apollo

2.3k Views Asked by At

Following some tutorials and examples, I integrated a GraphQL API into a simple Vue application. I'm using Apollo to interact with the API and graphql-tag's provided template literal to write the queries, like so:

gql`
    query getUser($userId: ID) {
        user(id: $userId) {
            name,
            email
        }
    }
`

However, I don't quite understand the necessity of the graphql-tag package. From what I understand, this package translates the query into AST, but what is the purpose of this in the frontend and why do you need graphql-tag package to do this? Can't GraphQL queries be sent to server as they are?

2

There are 2 best solutions below

3
On BEST ANSWER

The queries themselves can be sent to the server without being turned into a DocumentNode object. However, Apollo does not only send queries to your server. It implements a number of additional features, including normalized caching of the responses. For caching to work, we need to parse the provided queries into a machine-readable format. For example, by doing so, we can tell that all of these queries are in fact equivalent and can be fetched from the cache if we already have the data:

{
  foo
  bar
}

query SomeOperationName {
  foo
  bar
}

query { foo bar }

{
  bar
  qux: foo
}
0
On

They can be just plain strings, you can get IDE extensions to give you syntax highlighting where it sees the gql tag. Strings are inconvenient to manipulate, if you are trying to do things like add extra fields, merge multiple queries together, or other interesting stuff. It also semanticity separates the difference & importance of the following string.