说明: 本文是本人正在搞
nestjs+graphql+serverless
训练营中对Graphql
讲解的基础知识点,可能有点前后没对接上,文中提到的Graphql
授权也是下小节介绍的
一、对原来的Express
返回Graphql
项目修改
本章节使用的代码是
express
返回Graphql
的代码,在使用前要先对代码进行基本的配置,比如处理跨域问题(Graphql
本质也是发送一个http
请求,既然是这样在vue
项目中自然存在跨域的问题,需要先处理)
-
1、安装跨域的包,并且配置中间件
npm install cors 复制代码
const cors = require('cors'); // 处理跨域请求 app.use(cors()); 复制代码
-
2、配置获取请求体的中间件
// 处理请求 app.use(express.json());//express.json=bodyParser.json app.use(express.urlencoded({ extended: true })); 复制代码
二、在vue
中集成Graphql
-
1、参考文档地址
-
2、安装依赖包
npm install --save vue-apollo graphql apollo-boost graphql-tag 复制代码
-
3、在
src/main.js
中引入apollo-boost
模块并实例化ApolloClient
import ApolloClient from 'apollo-boost' ... const apolloClient = new ApolloClient({ // 你需要在这里使用绝对路径,这里就不区分环境开发了 uri: 'http://localhost:8000/graphql', }); ... 复制代码
-
4、在
src/main.js
配置vue-apollo
插件import VueApollo from 'vue-apollo' Vue.use(VueApollo); 复制代码
-
5、创建
Apollo provider
提供者,并且挂载到应用中import Vue from 'vue' import App from './App.vue' import ApolloClient from 'apollo-boost' import VueApollo from 'vue-apollo' Vue.use(VueApollo); Vue.config.productionTip = false const apolloClient = new ApolloClient({ // 你需要在这里使用绝对路径 uri: 'http://localhost:8000/graphql', }); const apolloProvider = new VueApollo({ defaultClient: apolloClient, }) new Vue({ render: h => h(App), // 挂载到应用 apolloProvider, }).$mount('#app') 复制代码
三、查询数据
-
1、使用
apollo
页面进来就查询数据根据官方的介绍,只用将
apolloProvider
挂载到了vue
中,在vue
的钩子函数中就会多一个属性apollo
<template> <div class="about"> {{accountList}} </div> </template> 复制代码
import gql from 'graphql-tag'; export default { name: 'About', apollo: { accountList: gql`query { accountList { id username password } }` }, } 复制代码
-
2、
apollo
中使用函数来调用import gql from 'graphql-tag'; export default { apollo: { accountList () { return { query: gql`query { accountList{ id username password created_at } }`, } }, } } 复制代码
-
3、点击按钮获取数据
import gql from 'graphql-tag'; // 定义查询的schema const accountListGql = gql`{ accountList { id username password } }`; export default { data() { return { tableList: [], } }, methods: { getTableData() { this.$apollo.addSmartQuery('accountList', { query: accountListGql, result(response) { console.log(response); const {accountList} = response.data; this.tableList = accountList; }, error(error) { console.log('请求失败', error); } }) } } } 复制代码
上面的方式也可以换成下面的写法,如果请求的业务不复杂可以这样写,如果复杂就根据上面的方式单独抽取一个
schema
... getTableData() { this.$apollo.addSmartQuery('accountList', { query: gql`{ accountList{ id username password } }`, result(response) { console.log(response); const {accountList} = response.data; this.tableList = accountList; }, error(error) { console.log('请求失败', error); } }) } ... 复制代码
-
4、传递参数的方式请求数据
handleClick (rowData) { this.$apollo.addSmartQuery('account', { query: gql` query($id: ID!) { account(id: $id) { id username password } } `, variables: { id: rowData.id, }, result (response) { console.log('查询单条数据', response.data); } }) } 复制代码
四、对查询数据方法改进
-
1、以上的方法可以查询数据,但是不能重复点击按钮,否则就会出现错误
-
2、改进版查询数据,直接使用
query
方法来查询getTableData () { this.$apollo.query({ query: gql`{ accountList{ id username password } }`, }).then(response => { console.log(response); const { accountList } = response.data; this.tableList =accountList; }) } 复制代码
五、使用mutation
添加数据
-
具体实现代码见下面
onSubmit () { this.$refs.form.validate(async (valid) => { if (valid) { console.log(this.form); const result = await this.$apollo.mutate({ mutation: gql` mutation addAccount($username: String!, $password: String!) { addAccount(username:$username,password: $password) } `, variables: { username: this.form.username, password: this.form.password, } }); console.log('更新结果', result); } else { // this.$message.error('请添加数据') return false; } }) } 复制代码
六、优化Graphql
请求
-
1、打开浏览器控制台点击请求
Graphql
接口的时候你会发现有下面三个参数
-
2、如果同一个数据或者说
variables
的值没变动的时候,是不会向后端发起请求的 -
3、
opertionName
是什么呢,我相信很多人会有疑问,看到下面两个图,我相信大家就不会疑惑了
这个操作名称就是在你使用
query
或者mutation
的时候的名字,这个命名可以随意命名,一般建议和后端的API
操作名保持一致。这个操作名有什么用呢?我们观察
Graphql
发送的请求都是同一个url
地址,我们在传统的Restful API
的时候,我们做登录鉴权或者获取url
的时候会就需要获取当前请求的地址,对于Graphql
来说,这个操作名也类似这个功能,区分是哪个API
来请求的。
七、优化代码
在传统的
Restful api
请求的时候,我们更倾向于在项目中创建一个services
的文件夹来将api
请求都放到一起,便于管理,很少将请求都写到vue
页面中去的。在graphql
中也可以如此操作,只是方式不一样。
-
1、在项目中创建一个
graphql
的文件夹,里面存放的类似Restful api
的接口请求 -
2、在
src/graphql/accountList.graphql
创建关于查询的接口query AccountList { accountList { id username password } } 复制代码
-
3、在
vue
中引入import AccountList from './../graphql/accountList.graphql'; ... methods: { async initTableData () { this.tableList = []; this.loading = true; const { data, loading } = await this.$apollo.query({ query: AccountList, }); console.log(data, '请求返回数据'); this.loading = loading; this.tableList = data.accountList; }, } ... 复制代码
-
4、不出意外的话会直接报错,因为
vue
不能直接识别graphql
文件,我们需要使用webpack
配置对应加载graphql
的loader
-
5、在项目根目录下创建一个
vue.config.js
配置loader
module.exports = { configureWebpack: (config) => { config.module.rules.push({ test: /\.(graphql|gql)$/, exclude: /node_modules/, loader: 'graphql-tag/loader' }) }, }; 复制代码
-
6、处理数据不刷新
上面每次新增数据、删除数据、修改数据,虽然我们调用了
initTableData
,但是Graphql
,并没有到后端,这是因为缓存的问题,需要在查询的时候添加红框圈住的字段就可以做到没次调用的时候,重新更新数据fetchPolicy: "no-cache", 复制代码
-
7、本章节整体的效果图
-
8、本小节的代码代码下载地址