GraphQL

学习GraphQL — 简介

2015-12-18  本文已影响39150人  时见疏星

GraphQL 是一个由Facebook提出的 应用层查询语言. 使用 GraphQL, 你可以基于图模式定义你的后端. 然后客户端就可以请求所需要的数据集。

GraphQL

因此, 你不必因为客户端数据需求的变更而改变你的后端. 这解决了管理REST API中的最大的问题.

GraphQL同样能够让客户端程序高效地批量获取数据. 例如, 看一看下面这个GraphQL请求:

{
  latestPost {
    _id,
    title,
    content,
    author {
      name
    },
    comments {
      content,
      author {
        name
      }
    }
  }
}

这个 GraphQL 请求获取了一篇博客文章和对应评论与作者信息的数据. 下面是请求的返回结果:

{
  "data": {
    "latestPost": {
      "_id": "03390abb5570ce03ae524397d215713b",
      "title": "New Feature: Tracking Error Status with Kadira",
      "content": "Here is a common feedback we received from our users ...",
      "author": {
        "name": "Pahan Sarathchandra"
      },
      "comments": [
        {
          "content": "This is a very good blog post",
          "author": {
            "name": "Arunoda Susiripala"
          }
        },
        {
          "content": "Keep up the good work",
          "author": {
            "name": "Kasun Indi"
          }
        }
      ]
    }
  }
}

如果你使用的是REST的话,你需要调用多个REST API的请求才能获取这些信息。

GraphQL是一个规范

因此, 它可以用于任何平台或语言. 它有一个参考的实现 JavaScript, 由Facebook维护. 还有许多社区维护的实现有许多种语言.

这里是它的规范:http://facebook.github.io/graphql/

一旦你使用了GraphQL,你会想在每个项目中使用它的。

上一篇下一篇

猜你喜欢

热点阅读