将服务器端的代码升级了一下:

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');

require("babel-polyfill");

var BASE_URL = 'http://localhost:3000';

var persons = [

{ id: "1", first_name: "Jack", last_name: "Zhang" , department: "Depart1", friends: [1] },

{ id: "2", first_name: "Tom", last_name: "Wang" , department: "Depart2", friends: [1, 2] }

];

function getPersonByUrl(args, relativeURL) {

var person = persons.find(function (item) {

if (args.id) {

return item.id == args.id;

}

if (args.department) {

return item.department == args.department;

}

});

return person;

//fetch('${BASE_URL}${relativeURL}')

//    .then(function (res) { return res.json() })

//    .then(function (json) { return json.person })

}

function getFriendByPersonId(friendID) {

var person = persons.find(function (item) {

return item.id == friendID;

});

return person;

//fetch('${BASE_URL}${relativeURL}')

//    .then(function (res) { return res.json() })

//    .then(function (json) { return json.person })

}

var PersonType = new GraphQLObjectType( {

name: 'Person',

description: '...',

fields: ()=>({

id: {

type: GraphQLString,

resolve : function (person) {

return person.first_name;

}

},

firstName: {

type: GraphQLString,

resolve : function (person) {

return person.first_name;

}

},

lastName: {

type: GraphQLString,

resolve : function (person) {

return person.last_name;

}

},

department: {

type: GraphQLString,

resolve : function (person) {

return person.department;

}

},

//email: { type: GraphQLString },

//userName: { type: GraphQLString },

//id: { type: GraphQLString },

friends: {

type: new GraphQLList(PersonType),

resolve: function (person) {

return person.friends.map(getFriendByPersonId);

}

}

})

});

var QueryType = new GraphQLObjectType({

name: 'Query',

desription: '...',

fields: {

person: {

type: PersonType,

args: {

id: { type: GraphQLString },

department: { type: GraphQLString }

},

resolve: function (obj, args, context, info) { return getPersonByUrl(args, null); }

}

}

});

var GraphQLSchemaObj = new GraphQLSchema({

query: QueryType

});

module.exports = GraphQLSchemaObj;

主要有以下几处更改:

  1. 将模拟的数据源persons单独提出来成为一个全局变量.
  2. 数据源中增加了department等几个属性.
  3. getPersonByUrl函数支持id和department参数.
  4. 增加了getFriendByPersonId函数用来解析friends属性.
  5. PersonType的fields属性使用了()=>来解决friends属性中使用本类型时本类型尚未初始化的问题.

下面是客户端的测试代码:

app.js

console.log('Hello world');

////Arguments

//var Test1 = require('./Test1');

//Test1.Execute();

////Alias

//var Test2 = require('./Test2');

//Test2.Execute();

////Alias with sub-selection

//var Test3 = require('./Test3');

//Test3.Execute();

////Fragments

//var Test4 = require('./Test4');

//Test4.Execute();

//Variblies

//var Test5 = require('./Test5');

//Test5.Execute();

//Directives

//var Test6 = require('./Test6');

//Test6.Execute();

具体的测试类:

Alias:

//Test2: Aliases

var gRequest = require('graphql-request').request;

exports.Execute = function () {

const query = '{'

+ '  Depart1Person: person(department: "Depart1") {'

+ '    firstName,'

+ '    lastName,'

+ '    department'

+ '  }'

+ '  Depart2Person: person(department: "Depart2") {'

+ '    firstName,'

+ '    lastName,'

+ '    department'

+ '  }'

+ '}';

gRequest('http://localhost:1337/graphql/graphql', query).then(function (data) { console.log(data) });

};

运行结果如下:

{ Depart1Person: { firstName: 'Jack', lastName: 'Zhang', department: 'Depart1' },

Depart2Person: { firstName: 'Tom', lastName: 'Wang', department: 'Depart2' } }

Aliases -- sub selection

//Test3: Aliases -- sub selection

var gRequest = require('graphql-request').request;

var util = require('util');

exports.Execute = function () {

const query = '{'

+ '  Depart1Person: person(department: "Depart1") {'

+ '    firstName,'

+ '    lastName,'

+ '    department,'

+ '    friends'

+ '    {'

+ '     firstName,'

+ '     lastName'

+ '    }'

+ '  }'

+ '  Depart2Person: person(department: "Depart2") {'

+ '    firstName,'

+ '    lastName,'

+ '    department,'

+ '    friends'

+ '    {'

+ '     firstName,'

+ '     lastName'

+ '    }'

+ '  }'

+ '}';

gRequest('http://localhost:1337/graphql/graphql', query).then(function (data) {

console.log(util.inspect(data, { showHidden: false, depth: null }))

});

};

运行结果如下:

{ Depart1Person:

{ firstName: 'Jack',

lastName: 'Zhang',

department: 'Depart1',

friends: [ { firstName: 'Jack', lastName: 'Zhang' } ] },

Depart2Person:

{ firstName: 'Tom',

lastName: 'Wang',

department: 'Depart2',

friends:

[ { firstName: 'Jack', lastName: 'Zhang' },

{ firstName: 'Tom', lastName: 'Wang' } ] } }

Fragements:

//Test4: Fragements

var gRequest = require('graphql-request').request;

var util = require('util');

exports.Execute = function () {

var query = '{'

+ '  Depart1Person: person(department: "Depart1") {'

+ '    ...personFields'

+ '  }'

+ '  Depart2Person: person(department: "Depart2") {'

+ '    ...personFields'

+ '  }'

+ '}'

+ ''

+ 'fragment personFields on Person {'

+ '  firstName,'

+ '  lastName,'

+ '  department,'

+ '  friends{'

+ '    firstName,'

+ '    lastName'

+ '  }'

+ '}';

//gRequest('http://localhost:1337/graphql/graphql', query).then(function (data) { console.log(data) });

gRequest('http://localhost:1337/graphql/graphql', query).then(function (data) {

console.log(util.inspect(data, { showHidden: false, depth: null }))

});

};

 

运行结果如下:

{ Depart1Person:

{ firstName: 'Jack',

lastName: 'Zhang',

department: 'Depart1',

friends: [ { firstName: 'Jack', lastName: 'Zhang' } ] },

Depart2Person:

{ firstName: 'Tom',

lastName: 'Wang',

department: 'Depart2',

friends:

[ { firstName: 'Jack', lastName: 'Zhang' },

{ firstName: 'Tom', lastName: 'Wang' } ] } }

Varibles:

//Test5: Variables

var gRequest = require('graphql-request').request;

var util = require('util');

exports.Execute = function () {

var query = 'query PersonWithDept($dept: String) {'

+ ' 
person(department: $dept) {'

+ '   
...personFields'

+ ' 
}'

+ '}'

+ ''

+ 'fragment personFields on Person {'

+ ' 
firstName,'

+ ' 
lastName,'

+ '  department,'

+ ' 
friends{'

+ '   
firstName,'

+ '   
lastName'

+ ' 
}'

+ '}';

var varibles =

{

"dept": "Depart1"

};

//gRequest('http://localhost:1337/graphql/graphql',
query).then(function (data) { console.log(data) });

gRequest('http://localhost:1337/graphql/graphql', query, varibles).then(function (data) {

console.log(util.inspect(data, {
showHidden: false, depth: null }))

});

};

运行结果如下:

{ person:

{ firstName: 'Jack',

lastName: 'Zhang',

department: 'Depart1',

friends: [ { firstName:
'Jack', lastName: 'Zhang' } ] } }

Directives:

//Test6: Directives

var gRequest = require('graphql-request').request;

var util = require('util');

exports.Execute = function () {

var query = 'query PersonWithDept($dept: String, $withFriends:
Boolean!) {'

+ '  person(department: $dept) {'

+ '    ...personFields'

+ '  }'

+ '}'

+ ''

+ 'fragment personFields on
Person {'

+ '  firstName,'

+ '  lastName,'

+ '  department,'

+ '  friends @include(if: $withFriends){'

+ '    firstName,'

+ '    lastName'

+ '  }'

+ '}' ;

var varibles1 =

{

"dept": "Depart1",

"withFriends": true

};

var varibles2 =

{

"dept": "Depart1",

"withFriends": false

};

//gRequest('http://localhost:1337/graphql/graphql',
query).then(function (data) { console.log(data) });

gRequest('http://localhost:1337/graphql/graphql', query, varibles1).then(function (data) {

console.log(util.inspect(data, {
showHidden: false, depth: null }))

});

gRequest('http://localhost:1337/graphql/graphql', query, varibles2).then(function (data) {

console.log(util.inspect(data, {
showHidden: false, depth: null }))

});

};

运行结果如下:

{ person: { firstName: 'Jack', lastName: 'Zhang', department:
'Depart1' } }

{ person:

{ firstName: 'Jack',

lastName: 'Zhang',

department: 'Depart1',

friends: [ { firstName:
'Jack', lastName: 'Zhang' } ] } }

注意客户端代码中使用了,是为了打印出json的子对象,

GraphQL入门2的更多相关文章

  1. Vue项目中GraphQL入门学习与应用

    1.GraphQL是什么,能干什么? 正如官网所说,GraphQL是一种用于API查询的语言.Facebook 的移动应用从 2012 年就开始使用 GraphQL.GraphQL 规范于 2015 ...

  2. GraphQL入门有这一篇就足够了

    GraphQL入门有这一篇就足够了:https://blog.csdn.net/qq_41882147/article/details/82966783 版权声明:本文为博主原创文章,遵循 CC 4. ...

  3. GraphQL入门1

    1. 资源: 主站: https://graphql.org/ 中文站: http://graphql.cn 入门视频: https://graphql.org/blog/rest-api-graph ...

  4. Graphql入门

    Graphql入门 GraphQL是一个查询语言,由Facebook开发,用于替换RESTful API.服务端可以用任何的语言实现.具体的你可以查看Facebook关于GraphQL的文档和各种语言 ...

  5. GraphQL 入门介绍

    写在前面 GraphQL是一种新的API标准,它提供了一种更高效.强大和灵活的数据提供方式.它是由Facebook开发和开源,目前由来自世界各地的大公司和个人维护.GraphQL本质上是一种基于api ...

  6. GraphQL入门3(Mutation)

    创建一个新的支持Mutation的Schema. var GraphQLSchema = require('graphql').GraphQLSchema; var GraphQLObjectType ...

  7. 《分享》Graphql入门与实践

    最近项目用到了graphql,学习了一些并在公司做了一个小分享,希望对你有帮助 一.介绍 Graphql是一种面向数据的API查询语言 Graphql给前端提供一种强力的查询工具,我们可以根据自己定义 ...

  8. GraphQL快速入门教程

    摘要: 体验神奇的GraphQL! 原文:GraphQL 入门详解 作者:MudOnTire Fundebug经授权转载,版权归原作者所有. GraphQL简介 定义 一种用于API调用的数据查询语言 ...

  9. 前端从零开始学习Graphql

    学习本姿势需要电脑装有node,vue-cli相关环境,以及要有node,express,koa,vue相关基础 本文相关demo的github地址: node服务:https://github.co ...

随机推荐

  1. HDU2873 Bomb Game(二维SG函数)

    Bomb Game Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others) Total ...

  2. VS2013 生成时复制文件或目录到指定目录

    需求: 在vs2010生成成功时将项目Lib目录下Reader文件夹内的所有文件和文件夹复制到输出目录(Debug或Release目录) 方法: 打开VS2010,右键项目属性-生成事件-后期生成事件 ...

  3. C#编程的语法积累(一)

    1.自动属性 之前的实现方式: private int id; public int Id { set {id = value;} get {return id;} } 现在可通过自动属性实现: pu ...

  4. 关于make: *** No rule to make target `clean'. Stop.这个莫名其妙问题的解决方法

    执行make编译命令总报错,后来试试make clean命令也不行,报下面的错. make: *** No rule to make target `clean'.  Stop. 真是莫名其妙的错误, ...

  5. windows下端口映射(端口转发)

    windows下端口映射(端口转发) 转载: https://blog.csdn.net/i1j2k3/article/details/70228043 本文是对网文的归纳整理,算不上原创,摸索过程亲 ...

  6. POJ 2752 (kmp求所有公共前后缀长度)

    <题目链接> <转载于> 题目大意:  给出一个字符串str,求出str中存在多少子串,使得这些子串既是str的前缀,又是str的后缀.从小到大依次输出这些子串的长度.即输出该 ...

  7. SpringMvc @ResponseBody

    一.@Response使用条件 二. @Response在最小配置.jackson的jar包情况下,json中包含的日期类型字段都是以时间戳long类型返回 三. Jack序列化对象转为JSON的限制 ...

  8. 每日踩坑 2018-01-09 WebAPI会如何面对 枚举 参数?

    这一块确实有些疑问, 众所周知 枚举参数我们传送枚举值所对应的数字就行了, 以前 Leader 跟我讲过,枚举参数会将字符串值也能够成功转化,而且枚举值定义之外的数字也可以被转为枚举值. 主要的问题在 ...

  9. BZOJ.2434.[NOI2011]阿狸的打字机(AC自动机 树状数组 DFS序)

    题目链接 首先不需要存储每个字符串,可以将所有输入的字符依次存进Trie树,对于每个'P',记录该串结束的位置在哪,以及当前节点对应的是第几个串(当前串即根节点到当前节点):对于'B',只需向上跳一个 ...

  10. BZOJ.2639.矩形计算(二维莫队)

    题目链接 二维莫队,按x,y坐标一起分块.(x,y)的所属的块为 x/sq(n)*sq(m) + y/sq(m) 排序时按照(左下点所在块,右上点的标号)排序 排序后 先得出一个询问的答案,然后利用上 ...