4

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?

Criss
  • 952
  • 5
  • 17

2 Answers2

7

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
}
Daniel Rearden
  • 80,636
  • 11
  • 185
  • 183
  • 1
    I don't get from your answer why graphql-tag is required, though, which seems to be what the OP is asking. – Mitya Jun 28 '21 at 16:20
  • @Mitya my understanding is that you don't need graphql-tag, but if you did have it, graphql-tag would help Apollo to recognise those objects as the same thing and cache them / reduce the amount of caching. i.e. it helps Apollo. – Jeremy Nov 05 '21 at 15:55
  • Interesting - thanks. – Mitya Nov 05 '21 at 18:29
2

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.

Dan Starns
  • 3,765
  • 1
  • 10
  • 28