1. 资源:
中文站: http://graphql.cn
入门视频: https://graphql.org/blog/rest-api-graphql-wrapper/ 这个网址中向下拉, 会看到这个入门视频:
   
从第15分钟看到第30分钟就可以.
官方Tutorial: https://graphql.org/graphql-js/mutations-and-input-types/
2. 服务器端代码示例.
a) 首先用VS2013新建一个Node.js express 4项目.
      
b) 添加一个router, 当然也可以直接用app.js.这里为了不影响其他router, 新建了一个router.
  

c) GraphQL.js的内容如下:
| var express = require('express'); var graphQLHTTP = require('express-graphql'); var schema = require('../schemas/Schema1'); var router = express.Router(); 
 router.use(graphQLHTTP({ schema: schema, graphiql : true })); 
 module.exports = router; | 
d) Schema1.js 的内容如下:
| var GraphQLSchema = require('graphql').GraphQLSchema; var GraphQLObjectType = require('graphql').GraphQLObjectType; var GraphQLString = require('graphql').GraphQLString; var GraphQLList = require('graphql').GraphQLList; var fetch = require('node-fetch'); 
 var BASE_URL = 'http://localhost:3000'; 
 function getPersonByUrl(relativeURL) { return { first_name: "Wang", last_name: "Tom" }; 
 //fetch('${BASE_URL}${relativeURL}') // .then(function (res) { return res.json() }) // .then(function (json) { return json.person }) } 
 var PersonType = new GraphQLObjectType({ name: 'Person', description: '...', fields: { firstName: { type: GraphQLString, resolve : function (person) { return person.first_name } }, lastName: { type: GraphQLString, resolve : function (person) { return person.last_name } }, //email: { type: GraphQLString }, //userName: { type: GraphQLString }, //id: { type: GraphQLString }, //friends: { // type: GraphQLList(PersonType), // resolve: function (person) { // return person.friends.map(getPersonByUrl); // } //} } }); 
 var QueryType = new GraphQLObjectType({ name: 'Query', desription: '...', fields: { person: { type: PersonType, args: { id: {type: GraphQLString} }, resolve: function () { return getPersonByUrl('/people/${args.id}') } } } 
 }); 
 var GraphQLSchemaObj = new GraphQLSchema({ query: QueryType }); 
 
 module.exports = GraphQLSchemaObj; | 
e) 代码中用到的node module都要装上.
f) VS中按F5运行起来后, http://localhost:<端口号>/<新建的router>就是基于GraphQL建立的router.
访问 http://localhost:<端口号>/<新建的router>/graphql就可以看到测试页面, 输入查询就可以看到结果.
    
router中的graphiql : true参数应该就是控制是否有这个测试页面的.
3. 客户端代码示例:
a) 建立一个Node console application.
 
b) 在app.js中写入如下的代码:
 
| console.log('Hello world'); 
 var gRequest = require('graphql-request').request; 
 const query = '{' + ' person(id:"1"){' + ' firstName' + ' }' + '}'; 
 gRequest('http://localhost:1337/graphql/graphql', query).then(function (data) { console.log(data) }); | 
执行node app.js后,结果如下:
 
4. 上面说的都是Node.js的版本, 其他语言的服务器和客户端的API看这个页面: http://graphql.cn/code/
 
                    
                 
 
                
            
         浙公网安备 33010602011771号
浙公网安备 33010602011771号