graphql浅出

12次阅读

共计 1792 个字符,预计需要花费 5 分钟才能阅读完成。

1. 初试牛刀

新建一个空项目,执行以下语句来安装 graphql

npm install graphql

将以下代码保存为hello.js

var {graphql, buildSchema} = require('graphql');

var schema = buildSchema(`
  type Query {hello: String}
`);

var root = {hello: () => 'Hello world!' };

graphql(schema, '{ hello}', root).then((response) => {console.log(response);
});

执行node hello.js,得到一段 JSON 数据

由以上部分可以看出,graphql 就是一个普通的函数

我们甚至可以将以上代码用在前端的代码框架中

2. 创建一个后端服务

创建以下代码,保存为 server.js
实现一个简单的 post 服务,并根据 body 中的 query 查询 graphql,返回相应数据。

var {graphql, buildSchema} = require("graphql");
const http = require("http");

var schema = buildSchema(`
  type Person {
    age: Int
    name: String
  }
  type Query {person(index: String): Person
  }
`);

var root = {person: function(param, context) {
    return {
      age: 18,
      name: "sj"
    };
  }
};

http
  .createServer((req, res) => {
    let body = "";
    req.on("data", data => {body += data;});
    req.on("end", () => {const { query, variables} = JSON.parse(body);
      const context = {db: "todo"};

      graphql(schema, query, root, context, variables).then(response => {res.end(JSON.stringify(response));
      });
    });
  })
  .listen(3000);

graphql 函数可以传递 5 个参数

  1. schema,定义一些 type 描述
  2. query,前端获取数据定义的结构,最后结果与其一致
  3. resolver,与 schema 中的 type 相对应的执行函数
  4. context,用于传递执行上下文,在 koa 或 express 中有重要作用
  5. variables,传递给执行函数的变量值

3. 客户端请求

使用 postman 模拟一次浏览器的请求

postman 中集合了 graphql 功能,发送的数据符合 graphql 客户端的标准请求格式

4. 框架

提到 graphql 不得不提两个重要框架

  • Apollo
  • Relay(Facebook)

由于,Apollo 在市面上的口碑较好、用法简单,且本人只使用过 Apollo,下面对其做简单介绍

5.Apollo 框架

作为 Relay 的竞品,Apollo 框架分为 server 和 client,个人认为 graphql 函数作为后端已经很简洁,不需要再引入 apollo 的 server 框架;

而 client 与 react 的结合,则可以让我们的前端 code 效率大大提升

例如一次性简单的数据查询,使用以下代码即可完成

function DogPhoto({breed}) {const { loading, error, data, refetch} = useQuery(GET_DOG_PHOTO, {variables: { breed},
    skip: !breed,
  });

  if (loading) return null;
  if (error) return `Error! ${error}`;

  return (
    <div>
      <img src={data.dog.displayImage} style={{height: 100, width: 100}} />
      <button onClick={() => refetch()}>Refetch!</button>
    </div>
  );
}

使用了这套 client 框架之后,你会发现可能不再需要使用 redux、saga 这样的全家桶,框架本身就能提供类似的服务。

广告

最近有没有对字节跳动感兴趣的同学,base:南京
有需要的请联系我邮箱:574745389@qq.com

正文完
 0