GraphQL

2020-07-16  本文已影响0人  紫雨杰

一、GraphQL是什么?

GraphQL 是一种查询语言、一个执行引擎,也是一种规范;
GraphQL 最大的优势是查询图状数据;
GraphQL对API中的数据提供了一套易于理解的完整描述,使得客户端能够准确的获取它需要的数据,而且没有任何冗余,也让API更容易随时间推移而演进;

官网:http://graphql.org
中文网: http://graphql.cn/

二、特点:

1、按需索取请求需要的数据,比如有多个字段,我们可以只取需要的某几个字段;
2、获取多个资源,只用一个请求;
3、API的演进无需划分版本,便于维护,根据需求平滑演进,添加或隐藏字段;

三、GraphQL 和 RestFul 的区别:

1、restful 一个接口只能返回一个资源,GraphQL 一次可以获取多个资源;
2、restFul使用不同的URL来区分资源,而GraphQL是用类型区分资源;

四、如何操作:

1、下载安装Node.js,node和npm会一起安装;
2、执行命令: npm init -y (-y 的目的是为了生成package.json);
3、执行命令:npm install express graphql express-graphql -S;
4、上述命令执行安装成功之后,执行js文件: node HelloWorld.js
5、访问:http://localhost:3000/graphql

简单的HelloWorld 代码:

const express = require('express');
const {buildSchema} = require('graphql');
const {graphqlHTTP} = require('express-graphql');


// 定义Schema,  查询方法和返回值类型
// Account 为自定义类型
const schema = buildSchema(`
  type Account {       //注意: Account 是自定义的类型
      name: String
      age: Int          //注意:Int首字母大写
      sex: String
      department: String 
  }
  
  type Query {
      hello: String
      accountName: String     //注意:字段之间没有逗号
      age: Int
      account: Account
  }
`)


//定义查询对应的处理器
const root = {
   hello: () => {
       return 'Hello World';
   },
   accountName: () => {
       return '李四';
   },
   age: () => {
       return 18;
   },
   account: () => {
      return {
        name: '张三',
        age: 19,                //注意:字段之间有逗号
        sex: '男',                      
        department: '开发部'
      }   
   }
}

const app = express();

app.use('/graphql', graphqlHTTP({
    schema: schema,
    rootValue: root,
    graphiql: true
}))

app.listen(3000);
helloworld.png
调试界面.png
上一篇下一篇

猜你喜欢

热点阅读