Graphql介绍
GraphQL 是一个用于 API 的查询语言,是一个使用基于类型系统来执行查询的服务端运行时(类型系统由你的数据定义)。
官方网站
Graphql Node egg 服务端接入零到一
一、搭建egg项目
已有egg项目,可直接进入第二步接入graphql。未创建项目,可快速搭建
推荐直接使用脚手架,可快速生成项目(npm >=6.1.0
):
$ mkdir egg-example && cd egg-example
$ npm init egg --type=simple
$ npm i
复制代码
启动项目:
$ npm run dev
$ open http://localhost:7001
复制代码
二、接入graphql
安装
npm i --save egg-graphql
复制代码
开启插件
// config/plugin.js
exports.graphql = {
enable: true,
package: 'egg-graphql',
};
复制代码
配置
// config/config.${env}.js
// ⚠️ 添加中间件拦截请求(必须)
exports.middleware = [ 'graphql' ];
// 配置(非必须)
exports.graphql = {
// 可视化界面路由
router: '/graphql',
// 是否加载到 app 上,默认开启
app: true,
// 是否加载到 agent 上,默认关闭
agent: false,
// 是否加载开发者工具 graphiql, 默认开启。路由同 router 字段。使用浏览器打开该可见。
graphiql: true,
//是否设置默认的Query和Mutation, 默认关闭
defaultEmptySchema:true,
// graphQL 路由前的拦截器
onPreGraphQL: function* (ctx) {},
// 开发工具 graphiQL 路由前的拦截器,建议用于做权限操作(如只提供开发者使用)
onPreGraphiQL: function* (ctx) {},
// apollo server的透传参数,参考[文档](https://www.apollographql.com/docs/apollo-server/api/apollo-server/#parameters)
apolloServerOptions: {
rootValue,
formatError,
formatResponse,
mocks,
schemaDirectives,
introspection,
playground,
debug,
validationRules,
tracing,
cacheControl,
subscriptions,
engine,
persistedQueries,
cors,
}
};
复制代码
使用graphql的egg目录结构
├── app
│ ├── controller
│ │ └── home.js
│ ├── graphql
│ │ ├── img
│ │ │ ├── connector.js // 处理取数逻辑(可选)
│ │ │ ├── resolver.js // 对查询或更改处理()
│ │ │ └── schema.graphql //1.描述数据,表明schema数据模型中有哪些字段
│ ├── router.js
│ └── service
├── config
│ ├── config.default.js
│ └── plugin.js
├── package.json
└── package-lock.json
复制代码
-
schema.graphql(必须)
(定义-数据)
描述数据,表明了一个数据模型中,有哪些字段。 -
resolver.js(必须)
(处理-数据)
处理用户的查询。针对暴露的查询接口,调用相应的connector 去取数。 -
connector.js(可选)
(取数-逻辑)
职责就是“取数”,插件去取数,还可以直接调用egg 的service 。
connector 已挂载到上下文,可直接使用ctx.connector 。
定义schema
// schema.graphql
# 定义查询(需要查询必须)
type Query {
imglist: [ImgData]
}
type ImgData {
id: String
name: String!
remark: String
deleted: Int
}
# 定义变更(需要变更必须)
type Mutation {
addImgList(name: String, remark: String, deleted: Int): ImgData
}
input addImgList {
name: String!
remark: String
deleted: Int
}
复制代码
schema.graphql
文件中,需要查询,就必须要定义 Query,需要变更,就必须要定义 Mutation
定义resolver
// resolve.js
const list = [
{
id: 1,
name: 'aaa',
remark: '备注',
deleted: 0,
},
{
id: 2,
name: 'bbb',
remark: '备注',
deleted: 0,
},
];
module.exports = {
// 查询
Query: {
imglist: () => {
return list;
},
},
// 变更
Mutation: {
addImgList(root, params, ctx) {
// ctx.connector
// console.log('root', root);
// console.log('ctx', ctx);
params.id = list.length++;
list.push(params);
return params;
},
},
};
复制代码
定义Query
和Mutation
,
运行
npm run dev
复制代码
// 访问 http://127.0.0.1:7001/graphql
// 查询语句
{
imglist {
id
name
}
}
复制代码
// 变更语句
mutation {
addImgList(name: "ccc", remark: "remark"){
name
remark
id
}
}
复制代码
以上完成了 Graphql 服务端的接入。接下来可以进行客户端的接入
Graphql 服务端如何结合sequelize,请往下看 “Graphql 结合 sequelize零到一”
Graphql Vue 客户端接入零到一
- vue-apollo
- Apollo Client(vue-apollo插件的底层)
安装
// 快速安装
vue add apollo
// 手动安装
复制代码
安装出现的问题 使用 vue add apolle 安装出现的问题
1.问题定位:疑似node的版本、npm 的版本、vue 的版本太旧
解决:查看版本(node -v;npm -v;vue -version),进行版本升级
node与npm:nodejs.org/en/ ,下载更新,更新node也就同时更新了npm
2.使用了@ali相关,vue add apolle时候,会重新install 相关依赖
解决:
删除已下载的node_modules文件夹,
package.json文件夹中 删除相关@ali的包
然后 执行vue add apolle
- 项目使用了
”node-sass": "^4.9.0",
"sass-loader": "^7.1.0",
配置
// src/vue-apollo.js
// 修改服务端接口为实际路径
const httpEndpoint = process.env.VUE_APP_GRAPHQL_HTTP || 'http://127.0.0.1:7001/graphql'
// 关闭ws,不使用subscriptions功能
wsEndpoint: null,
复制代码
使用(查询与变更)
查询
两种方式:
- 普通查询
- 智能查询,官方文档
<template>
<div> {{imglist}} </div>
</template>
import gql from 'graphql-tag'
export default {
//⚠️ 注意:imglist名称要相同
apollo: {
imglist: gql`query{
imglist {
id
name
}
}`
}
}
复制代码
变更
data(){
return {
name: 'gqlname',
remark: '备注'
}
}
// 执行mutate事件
this.$apollo
.mutate({
// gql需要定义各个值
mutation: gql`mutation($name:String!, $remark:String, $id:String, $deleted:Int) {
addImgList(name: $name, pid: $pid, id: $id, deleted:$deleted) {
name
remark
deleted
}
}`,
variables: {
data: {
name: this.name, // 可以使用this
remark: this.remark,
deleted: 0
}
}
})
.then((data) => {
console.log('成功', data)
})
.catch((error) => {
this.$message.error(error.message)
})
复制代码
Graphql 结合 sequelize零到一
待更新
参考
官网 graphql.cn
egg-graphql 插件 github.com/eggjs/egg-g…
apollo-server 官方Node端插件,基于expressjs github.com/apollograph…
教程 www.howtographql.com/graphql-js/…
apollo-client 官方前端插件 github.com/apollograph…
教程 React+apollo-client www.howtographql.com/react-apoll…