为什么你需要使用 Apollo 的 graphql-tag [英] Why do you need graphql-tag with Apollo

查看:43
本文介绍了为什么你需要使用 Apollo 的 graphql-tag的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据一些教程和示例,我将 GraphQL API 集成到一个简单的 Vue 应用程序中.我正在使用 Apollo 与 API 和 graphql-tag 提供的模板文字进行交互来编写查询,如下所示:

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

不过,我不太明白graphql-tag包的必要性.据我了解,这个包将查询转换为 AST,但是在前端这样做的目的是什么,为什么需要 graphql-tag 包来做到这一点?GraphQL 查询不能按原样发送到服务器吗?

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?

推荐答案

查询本身可以发送到服务器,而无需转换为 DocumentNode 对象.然而,Apollo 不会向您的服务器发送查询.它实现了许多附加功能,包括响应的规范化缓存.为了缓存工作,我们需要将提供的查询解析为机器可读的格式.例如,通过这样做,我们可以看出所有这些查询实际上是等效的,如果我们已经有了数据,就可以从缓存中获取:

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
}

这篇关于为什么你需要使用 Apollo 的 graphql-tag的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆