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?
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
}