GraphQL学习与实践1(入门介绍)

什么是GraphQL?
官方的解释:GraphQL是一门为API和运行时而生的查询语言。是一个由Facebook提出的应用层查询语言.通俗点来说,可以理解为基于RESTful的一种封装,一种新的api标准。

为什么要使用GraphQL?

  1. 所见即所得,相对RESTful API依赖于后端隐式的被动的数据约定,GraphQL更加显式,在获取数据和更新数据时更加主动。
  2. 减少网络请求的使用,GraphQL可以实现对多个数据源的调用,合并成一份完整的数据给前端使用。
  3. 参数类型强校验,GraphQL提供了强类型的schema机制,从而确保了参数类型的合法性。

准备
Prerequisites(先决条件):nodeV6或以上的版本,es6的一些语法糖。(官网上说,这些事例在nodeV6之前的版本还是可以使用。目前node稳定版本都在10.16以上了,所以…)

1、hello world

  1. 新建项目
C:\Users\Administrator\Desktop\graphql>npm init
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.

See `npm help json` for definitive documentation on these fields
and exactly what they do.

Use `npm install <pkg>` afterwards to install a package and
save it as a dependency in the package.json file.

Press ^C at any time to quit.
package name: (graphql) u-test1
version: (1.0.0)
description: graphql test
entry point: (index.js)
test command:
git repository:
keywords:
author: onsen
license: (ISC)
About to write to C:\Users\Administrator\Desktop\graphql\package.json:

{
  "name": "u-test1",
  "version": "1.0.0",
  "description": "graphql test",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "onsen",
  "license": "ISC"
}


Is this OK? (yes)

安装graphql

npm install graphql --save

编写代码,在根目录新建test-hello.js文件,输入:

var { graphql, buildSchema } = require('graphql');
// Construct a schema, using GraphQL schema language
var schema = buildSchema(`
  type Query {
    hello: String
  }
`);
// The root provides a resolver function for each API endpoint
var root = { hello: () => 'Hello world!' };
// Run the GraphQL query '{ hello }' and print out the response
graphql(schema, '{ hello }', root).then((response) => {
    console.log(response);
});

运行

node test-hello.js

结果:

C:\Users\Administrator\Desktop\graphql>node index.js
{ data: { hello: 'Hello world!' } }

过程分析:

  1. 创建一个 schema 来定义查询语句和类型,buildSchema() 方法需要传入的参数是字符串类型;
  2. 创建一个 root 处理器,处理对应的查询;
  3. 联合处理器和模型。

2、Express GraphQL服务器

Express作为一个流行的Node.js Web应用程序框架,为此搭建Express GraphQL服务器是学习GraphQL挺必要的一个东西。

基于Express GraphQL服务器的hello world

安装包模块:

npm install express express-graphql graphql

新建文件test2-express.js,输入:

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

var schema = buildSchema(`
  type Query {
    hello: String
  }
`);

var root = { hello: () => 'Hello world!' };

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

app.listen(4000, () => console.log('Now browse to localhost:4000/graphql'));

运行

node test2-express.js

打开浏览器,输入:http://localhost:4000/graphql
由于aphqlHTTP带着graphiql: true,此时打开上面的地址之后,会进入到GraphiQL工具输入查询的界面。然后在界面上输入:{ hello },点击运行,可以看到给出的一个结果,如下图所示:

在这里插入图片描述

使用客户端发送请求
在访问http://localhost:4000/graphql后,可以使用图形用户界面发送测试查询。如果要使用客户端发送请求则应当如何使用呢?

如图所示:
在这里插入图片描述
过程分析:

  1. 创建一个 schema 来定义查询语句和类型,buildSchema() 方法需要传入的参数是字符串类型;
  2. 创建一个 root 处理器,处理对应的查询;
  3. 实例化 express ,并且将路由转发给 graphqlHTTP 处理。

graphqlHTTP 中的三个参数介绍:
  schema:定义的查询语句和类型
  rootValue:处理对应查询的处理器
  graphiql:是否开启调试窗口,开发阶段开启,生产阶段关闭

3、基于apollo-server的Express GraphQL服务器

apollo-server是一套可以用于各种node.js框架(Express, Connect, Hapi, Koa etc)的GraphQL服务器的包。

安装包模块:
npm install apollo-server graphql

新建文件test2-apollo.js,输入:

const { ApolloServer, gql } = require('apollo-server');

var typeDefs = gql
    ` type Query { 
        hello: String
     } 
     schema { 
         query: Query 
     }`
;

var resolvers = {
    Query: {
        hello(root) {
            return 'world';
        }
    }
};

const server = new ApolloServer({ typeDefs, resolvers });
server.listen().then(({ url }) => {
    console.log(`?  Server ready at ${url}`);
  });

运行

node test2-apollo.js

C:\Users\Administrator\Desktop\graphql>node index.js
�  Server ready at http://localhost:4000/

打开浏览器,输入:http://localhost:4000/

然后在界面上输入:{ hello },点击运行,可以看到给出的一个结果,如下图所示:
在这里插入图片描述
备注:如果安装官网的指导直接使用,安装包:npm install apollo-server-express body-parser express graphql graphql-tools,然后用

var {graphqlExpress,graphiqlExpress}=require('apollo-server-express')

将会得到报错:graphqlExpress is not a function,详情可以参考apollo-server 2.0之后的更改,这里使用npm安装的是apollo-server@2.9.7的:
https://www.apollographql.com/docs/apollo-server/api/apollo-server

使用Apollo作为Express的中间件

修改test2-apollo.js文件为:

const { ApolloServer, gql } = require('apollo-server-express');

var typeDefs = gql
    ` type Query { 
        hello: String
     } 
     schema { 
         query: Query 
     }`
    ;

var resolvers = {
    Query: {
        hello(root) {
            return 'world';
        }
    }
};


const app = require('express')();

const server = new ApolloServer({ typeDefs, resolvers });
server.applyMiddleware({ app });
app.listen(4000, () => console.log('Now browse to localhost:4000/graphql'));

运行

node index.js

打开浏览器,输入:http://localhost:4000/graphql
然后在界面上输入:{ hello },点击运行,可以看到给出的一个结果,如下图所示:
在这里插入图片描述

更多

GraphQL学习与实践1(入门介绍)
GraphQL学习与实践2(类型、传参与构造函数类型)
GraphQL学习与实践3(Mutations And Input Types)
GraphQL学习与实践4(模拟客户端请求)
GraphQL学习与实践5(连接数据库mongodb与mysql)

代码:
onsenOnly:https://github.com/onsenOnly/graphql-test

有缘请点颗星,谢谢!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值