graphql是谷歌开发的一种查询语言,配合express-graphql能够快速的进行接口开发。而且,能够在允许,前端自由查询,操作某一个字段。更加自由,便捷。
在node中有成熟的中间件,express-graphql ,看看graphql官方给出的用例。
var express = require('express'); // 引入express
var {graphqlHTTP} = require('express-graphql'); // 引用express-graphql中间件
var { buildSchema } = require('graphql'); // 引入 graphql的的build方法,该方法能够对符合数据结构类似于protocol-buffers类型的数据,编译成schema 的对象
var schema = buildSchema(`
type Query {
hello: String
}
`); // buildSchema 的参数,这里的字符串格式,能够从一个以上数据结构的gql文件中,读取。
var root = { hello: () => 'Hello world!' }; // 返回结果, 如果是bff层,则从服务端获取数据,对象为每一个字段提供一个返回结果的函数。然后自动组装data形式的结果
var app = express(); // 构建express服务
app.use('/graphql', graphqlHTTP({
schema: schema,
rootValue: root,
graphql: true,
})); // 直接将graphqlHTTP服务,配置,并将返回的路由中间件挂载到 express的中间件上。
// 前端在访问改路由配到查询或者操作参数时,就能够得到返回结构
app.listen(8080, () => console.log('Now browse to localhost:8080/graphql'));
以上列子,我用注释对,每一个部分操作,进行了解读。方便理解。