新建一个空项目,执行如下语句来安装graphql前端
npm install graphql
将如下代码保存为hello.js
node
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数据react
由以上部分能够看出,graphql就是一个普通的函数
咱们甚至能够将以上代码用在前端的代码框架中express
建立如下代码,保存为server.js
。
实现一个简单的post服务,并根据body中的query查询graphql,返回相应数据。npm
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个参数
使用postman模拟一次浏览器的请求
postman中集合了graphql功能,发送的数据符合graphql客户端的标准请求格式redux
提到graphql不得不提两个重要框架后端
因为,Apollo在市面上的口碑较好、用法简单,且本人只使用过Apollo,下面对其作简单介绍浏览器
做为Relay的竞品,Apollo框架分为server和client,我的认为graphql函数做为后端已经很简洁,不须要再引入apollo的server框架;框架
而client与react的结合,则可让咱们的前端code效率大大提高koa
例如一次性简单的数据查询,使用如下代码便可完成
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