restful接口
- 粒度比较细
- 维护起来不太方便
- 每一个页面需要调用很多接口完成整个页面的所有功能
- 接口的响应格式不确定,restful 并没有明确规定接口的响应数据格式是怎么样的
graphql
- https://graphql.cn/
- 精确地获取你想要获取的数据项
-
什么是graphql
graphql目的的是为了简化前端和后端之间通信的规范
- 它主要由服务端的schema语言和客户端的查询语言组成
什么是apollo
- apollo是为了让你在你的应用中更好的是使用graphql进行开发
使用apollo开发
"apollo-server-express": "^2.4.8","axios": "^0.26.1","express": "^4.16.4","graphql": "^14.2.1"
const express = require('express');const { ApolloServer, gql } = require('apollo-server-express');const typeDefs = gql`type Query {hello: String}`;const resolvers = {Query: {hello: () => 'Hello world!',},};const server = new ApolloServer({ typeDefs, resolvers });const app = express();server.applyMiddleware({ app });app.listen({ port: 4000 }, () =>console.log('Now browse to http://localhost:4000' + server.graphqlPath));
客户端开发
- vue-apollo
- apollo-boost
```javascript import Vue from ‘vue’ import App from ‘./App.vue’ import moment from ‘moment’ import ‘./main.css’ Vue.config.productionTip = false{"name": "mydemo-client","version": "0.1.0","private": true,"scripts": {"serve": "vue-cli-service serve","build": "vue-cli-service build","lint": "vue-cli-service lint"},"dependencies": {"apollo-boost": "^0.3.1","core-js": "^2.6.5","graphql": "^14.2.1","moment": "^2.24.0","vue": "^2.6.10","vue-apollo": "^3.0.0-beta.28"},"devDependencies": {"@vue/cli-plugin-babel": "^3.6.0","@vue/cli-plugin-eslint": "^3.6.0","@vue/cli-service": "^3.6.0","babel-eslint": "^10.0.1","eslint": "^5.16.0","eslint-plugin-vue": "^5.0.0","vue-template-compiler": "^2.5.21"},"eslintConfig": {"root": true,"env": {"node": true},"extends": ["plugin:vue/essential","eslint:recommended"],"rules": {},"parserOptions": {"parser": "babel-eslint"}},"postcss": {"plugins": {"autoprefixer": {}}},"browserslist": ["> 1%","last 2 versions","not ie <= 8"]}
// 自定义Vue过滤器,格式化时间 Vue.filter(‘formatDate’, function(value, format) { // 格式化时间 let d = new Date(parseInt(value)) return moment(d).format(format) })
// 导入apollo相关插件 import VueApollo from ‘vue-apollo’ Vue.use(VueApollo)
// 产生apollo客户端实例对象 import ApolloClient from ‘apollo-boost’ const apolloClient = new ApolloClient({ uri: ‘http://localhost:4001/graphql‘ }) const apolloProvider = new VueApollo({ defaultClient: apolloClient, })
// 把apollo实例对象挂载到Vue实例中 new Vue({ apolloProvider, render: h => h(App), }).$mount(‘#app’)
```vue<template><div class="content"><div class="wrap"><form><div class="box"><textarea name="content" v-model='content'></textarea></div><div class="publish">您的大名:<input type="text" autocomplete="off" v-model='username'><button class="W_btn" @click.prevent='send'>发布</button></div></form></div><div class="list"><ul><li :key='index' v-for='(item, index) in info.list'><img src="../assets/timg.jpg" alt="" class="pic"><div class="list_con"><div class="time"><strong>发表时间: <i>{{item.date | formatDate('YYYY-MM-DD hh:mm:ss')}}</i></strong><img src="images/lj.jpg" alt=""></div><p><b>{{item.username}}:</b>{{item.content}}</p></div></li></ul></div><div class="link"><a :key='index' :href="item.lurl" v-for='(item, index) in info.link'>{{item.lname}}</a></div><div class="weather"><div>天气:{{info.weather && info.weather.wea}}</div><div>温度:{{info.weather && info.weather.temp}}</div></div></div></template><script>// 导入apollo客户端相关apiimport gql from 'graphql-tag';const QueryListTag = gql`query info {info {list {usernamecontentdate}link {lnamelurl}weather {weatemp}}}`export default {name: 'Comment',apollo: {info: {query: QueryListTag}},data () {return {// info表示服务端返回的数据info: {list: [],link: [],weather: {}},username: '',content: ''}},methods: {send: function() {// console.log(this.username, this.content)// 把表单的数据通过接口提交到服务器this.$apollo.mutate({mutation: gql`mutation createComment($commentInput: CommentInput) {createComment(commentInput: $commentInput) {usernamecontent}}`,variables: {commentInput: {username: this.username,content: this.content}},refetchQueries: [{query: QueryListTag}]})}}}</script>
内置类型
- Int
- String
- Boolean
- Float
- ID:利用uuid,保证id不重复
- enum
杂记
- 表示列表
- ! 表示非空
- [String!] 数组本身可以为空,但是内容项不能为空
- [String]! 数组本身不能为空,但是内容项可以为空
输入类型
input UserInput {uname: String}
Mutation
- 定义Mutation,可以用来接收客户端传递的 input 类型数据,用于变更
- type Mutation
- Query 是默认的查询类型,再服务端必须存在,且唯一
- 通过 type 关键字定义类型
- type 之后是类型名称,可以自定义
- graphql 使用 # 进行注释
- Query的时候,如果是数组和对象,需要指明要获取哪些属性 ```javascript // 变更 // 改变服务器数据需要使用到变更
const express = require(‘express’); const { ApolloServer, gql } = require(‘apollo-server-express’);
const typeDefs = gql`
# 输入类型input UserInfo {uname: Stringpwd: String}enum Favour {SWIMMINGCODEING}type User {id: ID,uname: Stringpwd: String}type Query {hello: Stringinfo: Favour}# 变更类型type Mutation {addUserByInput(userInput: UserInfo): User}
`;
const context = () => { return { db: ‘dbObj’ } }
const resolvers = { Query: { /**
* @param {*} parent 当前字段的父级对象* @param {*} args* @param {*} context* @param {*} info* @returns*/hello: (parent, args, context, info) => {return context.db},info: () => {// 只能返回枚举中定义的那些值return 'SWIMMING'}
}, Mutation: { addUserByInput: (obj, args) => { return { id: 1, uname: args.userInput.uname, pwd: args.userInput.pwd } } } };
const server = new ApolloServer({ typeDefs, resolvers, context });
const app = express(); server.applyMiddleware({ app });
app.listen({ port: 3000 }, () => console.log(‘Now browse to http://localhost:3000‘ + server.graphqlPath) );
```javascript// 变更// 改变服务器数据需要使用到变更const express = require('express');const { ApolloServer, gql } = require('apollo-server-express');const typeDefs = gql`# 输入类型input UserInfo {uname: Stringpwd: String}# 用户类型type User {id: ID,uname: Stringpwd: String}# 查询类型type Query {hello: String}# 变更类型type Mutation {addUserByInput(userInput: UserInfo): UseraddUserByParam(uname: String, pwd: String): User}`;const resolvers = {Query: {hello: () => "Hello World"},Mutation: {addUserByInput: (obj, args) => {return {id: 1,uname: args.userInput.uname,pwd: args.userInput.pwd}},addUserByParam: (obj, args) => {return {id: 2,uname: args.uname,pwd: args.pwd}}}};const server = new ApolloServer({ typeDefs, resolvers });const app = express();server.applyMiddleware({ app });app.listen({ port: 3000 }, () =>console.log('Now browse to http://localhost:3000' + server.graphqlPath));/*mutation addUserByParam {addUserByParam(uname: "张三", pwd: "123") {idunamepwd}}mutation addUserByInput($userInput: UserInfo) {addUserByInput(userInput: $userInput){idunamepwd}}*/
别名
// 别名// 有时候需要通过不同参数值查询相同字段信息,比如查询学生的数学和英语成绩const express = require('express')const { ApolloServer, gql } = require('apollo-server-express')const typeDefs = gql`# 课程类型type Course {cname: Stringscore: Float}# 学生类型type Student {id: Intsname: Stringage: Intscores(cname: String): [Course]}# 查询类型type Query {hello: Stringstu: Student}`const resolvers = {Student: {scores: (parent, args) => {if (args.cname == "数学" || args.cname == "英语") {return parent.scores.filter(item => {return item.cname == args.cname})} else {return parent.scores}}},Query: {hello: () => "Hello World",stu: (parent, args) => {return {id: 1,sname: '张三',scores: [{cname: '数学',score: 99.5},{cname: '英语',score: 91.5},{cname: '语文',score: 79.5}]}}}}const server = new ApolloServer({typeDefs,resolvers})const app = express()server.applyMiddleware({ app })app.listen(3001, () => {console.log("server is running");})// query alias {// stu {// sname// math: scores(cname: "数学") {// cname// score// }// }// }
参数
const express = require('express')const { ApolloServer, gql } = require('apollo-server-express')// 定义数据类型// Query 是默认的查询类型,再服务端必须存在,且唯一// 通过 type 关键字定义类型// type 之后是类型名称(可以自定义)// graphql 使用 # 进行注释// Query的时候,如果想要数组和对象的数据,需要指明要获取哪些属性const typeDfs = gql`# 课程类型type Course {cname: String,score: Float}type Student {sname: String,age: Int}# Query 是查询入口type Query {hello: Stringstu(n: Int, address: String, a: Int = 1): Student}`// 解析数据类型对应的具体数据const resolvers = {Query: {hello: () => "哈哈",// 可以定义字段参数,也可以有默认值stu: (obj, args) => {// { n: 199, address: '上海' }console.log(args)return {sname: "张三",age: 23}}}}// 整合apollo-server和expressconst server = new ApolloServer({// 这两个属性名是固定的typeDefs: typeDfs,resolvers: resolvers})const app = express()server.applyMiddleware({ app })// 启动监听app.listen(3000, () => {console.log('server is running')})
Context
const express = require('express')const { ApolloServer, gql } = require('apollo-server-express')const db = require('./db')const typeDefs = gql`type Student {name: Stringage: Int}# 查询类型type Query {hello: [Student!]!}`const resolvers = {Query: {hello: async (parent, args, context) => {let ret = await context.db.getData()return JSON.parse(ret)}}}const context = () => {return {db: db}}const server = new ApolloServer({typeDefs,resolvers,context})const app = express()server.applyMiddleware({ app })app.listen(3001, () => {console.log("server is running");})
指令
// 指令// 有时候查询的字段数量不是固定的,此时可以通过指令的方式进行控制// 控制某一字段值是否显示// 指令用到的变量定义时需要加 !,强制必须提供该值const express = require('express')const { ApolloServer, gql } = require('apollo-server-express')const typeDefs = gql`# 学生类型type Student {id: Intsname: Stringgender: Boolean}# 查询类型type Query {hello: Stringstu(id: Int): Student}`const resolvers = {Query: {hello: () => "Hello World",stu: (parent, args) => {if (args.id == 1) {return {id: 1,sname: '张三',gender: true}} else {return {id: 0,sname: '---',gender: false}}}}}const server = new ApolloServer({typeDefs,resolvers})const app = express()server.applyMiddleware({ app })app.listen(3001, () => {console.log("server is running");})// @include(id: Boolean) 仅在参数为true的时候,包含此字段// @skip(if: Boolean) 如果参数为true,跳过此字段// query directive($id: Int, $gender: Boolean!) {// stu(id: $id) {// id// sname// gender @include(if: $gender)// }// }// {// "id": 1,// "gender": false// }
枚举
const express = require('express');const { ApolloServer, gql } = require('apollo-server-express');const typeDefs = gql`enum Favour {SWIMMINGCODEING}type Query {hello: Stringinfo: Favour}`;const resolvers = {Query: {hello: () => 'Hello world!',info: () => {// 只能返回枚举中定义的那些值return 'SWIMMING'}},};const server = new ApolloServer({ typeDefs, resolvers });const app = express();server.applyMiddleware({ app });app.listen({ port: 3000 }, () =>console.log('Now browse to http://localhost:3000' + server.graphqlPath));
parent
const express = require('express')const { ApolloServer, gql } = require('apollo-server-express')const typeDefs = gql`type Student {sname: Stringage: Intfavour: String}# 查询类型type Query {hello: Stringstu: Student}`const resolvers = {Student: {sname: (parent) => {// 这个时候 parent 参数才有用console.log(parent);return "zhangsan"},favour: (parent) => {// 可以对父节点传入的数据进行一些加工处理if (parent.favour == 'SWIMMING') {return '游泳'} else {return parent.favour}}},Query: {hello: () => 'hello world',// 对于根节点来说,parent参数没有用// context: 用于获取数据源对象stu: (parent, args, context) => {console.log(context.db)return {// 获取sname,获取的是 zhangsansname: "张三"}}}}const context = () => {return {db: 'dbData'}}const server = new ApolloServer({typeDefs,resolvers,context})const app = express()server.applyMiddleware({ app })app.listen(3001, () => {console.log("server is running");})
变量
// 变量的使用// 变量类型必须是标量// 变量可以有默认值 ($id: Int = 1)const express = require('express')const { ApolloServer, gql } = require('apollo-server-express')const typeDefs = gql`# 课程类型type Course {cname: Stringscore: Float}# 学生类型type Student {id: Intsname: Stringage: Intscores(num: Float): [Course]}# 查询类型type Query {hello: Stringstu(id: Int): Student}`const resolvers = {Student: {scores: (parent, args) => {return parent.scores && parent.scores.filter(item => {return item.score > args.num})}},Query: {hello: () => "Hello World",stu: (parent, args) => {if (args.id == 1) {return {id: 1,sname: '张三',scores: [{cname: '数学',score: 99.5},{cname: '英语',score: 98.5}]}} else {return {id: 0,sname: '---',score: null}}}}}const server = new ApolloServer({typeDefs,resolvers})const app = express()server.applyMiddleware({ app })app.listen(3001, () => {console.log("server is running");})// 多字段 参数传递// query param($id: Int, $num: Float) {// stu(id: $id) {// sname// scores(num: $num) {// cname// score// }// }// }// {// "id": 1,// "num": 95// }
