restful接口

  1. 粒度比较细
  2. 维护起来不太方便
  3. 每一个页面需要调用很多接口完成整个页面的所有功能
  4. 接口的响应格式不确定,restful 并没有明确规定接口的响应数据格式是怎么样的

graphql

  1. https://graphql.cn/
  2. 精确地获取你想要获取的数据项
  3. 获取多个资源的时候,只要一个请求

    什么是graphql

  4. graphql目的的是为了简化前端和后端之间通信的规范

  5. 它主要由服务端的schema语言和客户端的查询语言组成

什么是apollo

  1. apollo是为了让你在你的应用中更好的是使用graphql进行开发

使用apollo开发

  1. "apollo-server-express": "^2.4.8",
  2. "axios": "^0.26.1",
  3. "express": "^4.16.4",
  4. "graphql": "^14.2.1"
  1. const express = require('express');
  2. const { ApolloServer, gql } = require('apollo-server-express');
  3. const typeDefs = gql`
  4. type Query {
  5. hello: String
  6. }
  7. `;
  8. const resolvers = {
  9. Query: {
  10. hello: () => 'Hello world!',
  11. },
  12. };
  13. const server = new ApolloServer({ typeDefs, resolvers });
  14. const app = express();
  15. server.applyMiddleware({ app });
  16. app.listen({ port: 4000 }, () =>
  17. console.log('Now browse to http://localhost:4000' + server.graphqlPath)
  18. );

客户端开发

  1. vue-apollo
  2. apollo-boost
    1. {
    2. "name": "mydemo-client",
    3. "version": "0.1.0",
    4. "private": true,
    5. "scripts": {
    6. "serve": "vue-cli-service serve",
    7. "build": "vue-cli-service build",
    8. "lint": "vue-cli-service lint"
    9. },
    10. "dependencies": {
    11. "apollo-boost": "^0.3.1",
    12. "core-js": "^2.6.5",
    13. "graphql": "^14.2.1",
    14. "moment": "^2.24.0",
    15. "vue": "^2.6.10",
    16. "vue-apollo": "^3.0.0-beta.28"
    17. },
    18. "devDependencies": {
    19. "@vue/cli-plugin-babel": "^3.6.0",
    20. "@vue/cli-plugin-eslint": "^3.6.0",
    21. "@vue/cli-service": "^3.6.0",
    22. "babel-eslint": "^10.0.1",
    23. "eslint": "^5.16.0",
    24. "eslint-plugin-vue": "^5.0.0",
    25. "vue-template-compiler": "^2.5.21"
    26. },
    27. "eslintConfig": {
    28. "root": true,
    29. "env": {
    30. "node": true
    31. },
    32. "extends": [
    33. "plugin:vue/essential",
    34. "eslint:recommended"
    35. ],
    36. "rules": {},
    37. "parserOptions": {
    38. "parser": "babel-eslint"
    39. }
    40. },
    41. "postcss": {
    42. "plugins": {
    43. "autoprefixer": {}
    44. }
    45. },
    46. "browserslist": [
    47. "> 1%",
    48. "last 2 versions",
    49. "not ie <= 8"
    50. ]
    51. }
    ```javascript import Vue from ‘vue’ import App from ‘./App.vue’ import moment from ‘moment’ import ‘./main.css’ Vue.config.productionTip = false

// 自定义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’)

  1. ```vue
  2. <template>
  3. <div class="content">
  4. <div class="wrap">
  5. <form>
  6. <div class="box">
  7. <textarea name="content" v-model='content'></textarea>
  8. </div>
  9. <div class="publish">
  10. 您的大名:
  11. <input type="text" autocomplete="off" v-model='username'>
  12. <button class="W_btn" @click.prevent='send'>发布</button>
  13. </div>
  14. </form>
  15. </div>
  16. <div class="list">
  17. <ul>
  18. <li :key='index' v-for='(item, index) in info.list'>
  19. <img src="../assets/timg.jpg" alt="" class="pic">
  20. <div class="list_con">
  21. <div class="time">
  22. <strong>发表时间: <i>{{item.date | formatDate('YYYY-MM-DD hh:mm:ss')}}</i></strong>
  23. <img src="images/lj.jpg" alt="">
  24. </div>
  25. <p><b>{{item.username}}:</b>{{item.content}}</p>
  26. </div>
  27. </li>
  28. </ul>
  29. </div>
  30. <div class="link">
  31. <a :key='index' :href="item.lurl" v-for='(item, index) in info.link'>{{item.lname}}</a>
  32. </div>
  33. <div class="weather">
  34. <div>天气:{{info.weather && info.weather.wea}}</div>
  35. <div>温度:{{info.weather && info.weather.temp}}</div>
  36. </div>
  37. </div>
  38. </template>
  39. <script>
  40. // 导入apollo客户端相关api
  41. import gql from 'graphql-tag';
  42. const QueryListTag = gql`
  43. query info {
  44. info {
  45. list {
  46. username
  47. content
  48. date
  49. }
  50. link {
  51. lname
  52. lurl
  53. }
  54. weather {
  55. wea
  56. temp
  57. }
  58. }
  59. }
  60. `
  61. export default {
  62. name: 'Comment',
  63. apollo: {
  64. info: {
  65. query: QueryListTag
  66. }
  67. },
  68. data () {
  69. return {
  70. // info表示服务端返回的数据
  71. info: {
  72. list: [],
  73. link: [],
  74. weather: {}
  75. },
  76. username: '',
  77. content: ''
  78. }
  79. },
  80. methods: {
  81. send: function() {
  82. // console.log(this.username, this.content)
  83. // 把表单的数据通过接口提交到服务器
  84. this.$apollo.mutate({
  85. mutation: gql`
  86. mutation createComment($commentInput: CommentInput) {
  87. createComment(commentInput: $commentInput) {
  88. username
  89. content
  90. }
  91. }
  92. `,
  93. variables: {
  94. commentInput: {
  95. username: this.username,
  96. content: this.content
  97. }
  98. },
  99. refetchQueries: [{
  100. query: QueryListTag
  101. }]
  102. })
  103. }
  104. }
  105. }
  106. </script>

内置类型

  1. Int
  2. String
  3. Boolean
  4. Float
  5. ID:利用uuid,保证id不重复
  6. enum

杂记

  1. 表示列表
  2. ! 表示非空
  3. [String!] 数组本身可以为空,但是内容项不能为空
  4. [String]! 数组本身不能为空,但是内容项可以为空

输入类型

  1. input UserInput {
  2. uname: String
  3. }

Mutation

  1. 定义Mutation,可以用来接收客户端传递的 input 类型数据,用于变更
  2. type Mutation
  3. Query 是默认的查询类型,再服务端必须存在,且唯一
  4. 通过 type 关键字定义类型
  5. type 之后是类型名称,可以自定义
  6. graphql 使用 # 进行注释
  7. Query的时候,如果是数组和对象,需要指明要获取哪些属性 ```javascript // 变更 // 改变服务器数据需要使用到变更

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

const typeDefs = gql`

  1. # 输入类型
  2. input UserInfo {
  3. uname: String
  4. pwd: String
  5. }
  6. enum Favour {
  7. SWIMMING
  8. CODEING
  9. }
  10. type User {
  11. id: ID,
  12. uname: String
  13. pwd: String
  14. }
  15. type Query {
  16. hello: String
  17. info: Favour
  18. }
  19. # 变更类型
  20. type Mutation {
  21. addUserByInput(userInput: UserInfo): User
  22. }

`;

const context = () => { return { db: ‘dbObj’ } }

const resolvers = { Query: { /**

  1. * @param {*} parent 当前字段的父级对象
  2. * @param {*} args
  3. * @param {*} context
  4. * @param {*} info
  5. * @returns
  6. */
  7. hello: (parent, args, context, info) => {
  8. return context.db
  9. },
  10. info: () => {
  11. // 只能返回枚举中定义的那些值
  12. return 'SWIMMING'
  13. }

}, 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) );

  1. ```javascript
  2. // 变更
  3. // 改变服务器数据需要使用到变更
  4. const express = require('express');
  5. const { ApolloServer, gql } = require('apollo-server-express');
  6. const typeDefs = gql`
  7. # 输入类型
  8. input UserInfo {
  9. uname: String
  10. pwd: String
  11. }
  12. # 用户类型
  13. type User {
  14. id: ID,
  15. uname: String
  16. pwd: String
  17. }
  18. # 查询类型
  19. type Query {
  20. hello: String
  21. }
  22. # 变更类型
  23. type Mutation {
  24. addUserByInput(userInput: UserInfo): User
  25. addUserByParam(uname: String, pwd: String): User
  26. }
  27. `;
  28. const resolvers = {
  29. Query: {
  30. hello: () => "Hello World"
  31. },
  32. Mutation: {
  33. addUserByInput: (obj, args) => {
  34. return {
  35. id: 1,
  36. uname: args.userInput.uname,
  37. pwd: args.userInput.pwd
  38. }
  39. },
  40. addUserByParam: (obj, args) => {
  41. return {
  42. id: 2,
  43. uname: args.uname,
  44. pwd: args.pwd
  45. }
  46. }
  47. }
  48. };
  49. const server = new ApolloServer({ typeDefs, resolvers });
  50. const app = express();
  51. server.applyMiddleware({ app });
  52. app.listen({ port: 3000 }, () =>
  53. console.log('Now browse to http://localhost:3000' + server.graphqlPath)
  54. );
  55. /*
  56. mutation addUserByParam {
  57. addUserByParam(uname: "张三", pwd: "123") {
  58. id
  59. uname
  60. pwd
  61. }
  62. }
  63. mutation addUserByInput($userInput: UserInfo) {
  64. addUserByInput(userInput: $userInput){
  65. id
  66. uname
  67. pwd
  68. }
  69. }
  70. */

别名

  1. // 别名
  2. // 有时候需要通过不同参数值查询相同字段信息,比如查询学生的数学和英语成绩
  3. const express = require('express')
  4. const { ApolloServer, gql } = require('apollo-server-express')
  5. const typeDefs = gql`
  6. # 课程类型
  7. type Course {
  8. cname: String
  9. score: Float
  10. }
  11. # 学生类型
  12. type Student {
  13. id: Int
  14. sname: String
  15. age: Int
  16. scores(cname: String): [Course]
  17. }
  18. # 查询类型
  19. type Query {
  20. hello: String
  21. stu: Student
  22. }
  23. `
  24. const resolvers = {
  25. Student: {
  26. scores: (parent, args) => {
  27. if (args.cname == "数学" || args.cname == "英语") {
  28. return parent.scores.filter(item => {
  29. return item.cname == args.cname
  30. })
  31. } else {
  32. return parent.scores
  33. }
  34. }
  35. },
  36. Query: {
  37. hello: () => "Hello World",
  38. stu: (parent, args) => {
  39. return {
  40. id: 1,
  41. sname: '张三',
  42. scores: [
  43. {
  44. cname: '数学',
  45. score: 99.5
  46. },
  47. {
  48. cname: '英语',
  49. score: 91.5
  50. },
  51. {
  52. cname: '语文',
  53. score: 79.5
  54. }
  55. ]
  56. }
  57. }
  58. }
  59. }
  60. const server = new ApolloServer({
  61. typeDefs,
  62. resolvers
  63. })
  64. const app = express()
  65. server.applyMiddleware({ app })
  66. app.listen(3001, () => {
  67. console.log("server is running");
  68. })
  69. // query alias {
  70. // stu {
  71. // sname
  72. // math: scores(cname: "数学") {
  73. // cname
  74. // score
  75. // }
  76. // }
  77. // }

参数

  1. const express = require('express')
  2. const { ApolloServer, gql } = require('apollo-server-express')
  3. // 定义数据类型
  4. // Query 是默认的查询类型,再服务端必须存在,且唯一
  5. // 通过 type 关键字定义类型
  6. // type 之后是类型名称(可以自定义)
  7. // graphql 使用 # 进行注释
  8. // Query的时候,如果想要数组和对象的数据,需要指明要获取哪些属性
  9. const typeDfs = gql`
  10. # 课程类型
  11. type Course {
  12. cname: String,
  13. score: Float
  14. }
  15. type Student {
  16. sname: String,
  17. age: Int
  18. }
  19. # Query 是查询入口
  20. type Query {
  21. hello: String
  22. stu(n: Int, address: String, a: Int = 1): Student
  23. }
  24. `
  25. // 解析数据类型对应的具体数据
  26. const resolvers = {
  27. Query: {
  28. hello: () => "哈哈",
  29. // 可以定义字段参数,也可以有默认值
  30. stu: (obj, args) => {
  31. // { n: 199, address: '上海' }
  32. console.log(args)
  33. return {
  34. sname: "张三",
  35. age: 23
  36. }
  37. }
  38. }
  39. }
  40. // 整合apollo-server和express
  41. const server = new ApolloServer({
  42. // 这两个属性名是固定的
  43. typeDefs: typeDfs,
  44. resolvers: resolvers
  45. })
  46. const app = express()
  47. server.applyMiddleware({ app })
  48. // 启动监听
  49. app.listen(3000, () => {
  50. console.log('server is running')
  51. })

Context

  1. const express = require('express')
  2. const { ApolloServer, gql } = require('apollo-server-express')
  3. const db = require('./db')
  4. const typeDefs = gql`
  5. type Student {
  6. name: String
  7. age: Int
  8. }
  9. # 查询类型
  10. type Query {
  11. hello: [Student!]!
  12. }
  13. `
  14. const resolvers = {
  15. Query: {
  16. hello: async (parent, args, context) => {
  17. let ret = await context.db.getData()
  18. return JSON.parse(ret)
  19. }
  20. }
  21. }
  22. const context = () => {
  23. return {
  24. db: db
  25. }
  26. }
  27. const server = new ApolloServer({
  28. typeDefs,
  29. resolvers,
  30. context
  31. })
  32. const app = express()
  33. server.applyMiddleware({ app })
  34. app.listen(3001, () => {
  35. console.log("server is running");
  36. })

指令

  1. // 指令
  2. // 有时候查询的字段数量不是固定的,此时可以通过指令的方式进行控制
  3. // 控制某一字段值是否显示
  4. // 指令用到的变量定义时需要加 !,强制必须提供该值
  5. const express = require('express')
  6. const { ApolloServer, gql } = require('apollo-server-express')
  7. const typeDefs = gql`
  8. # 学生类型
  9. type Student {
  10. id: Int
  11. sname: String
  12. gender: Boolean
  13. }
  14. # 查询类型
  15. type Query {
  16. hello: String
  17. stu(id: Int): Student
  18. }
  19. `
  20. const resolvers = {
  21. Query: {
  22. hello: () => "Hello World",
  23. stu: (parent, args) => {
  24. if (args.id == 1) {
  25. return {
  26. id: 1,
  27. sname: '张三',
  28. gender: true
  29. }
  30. } else {
  31. return {
  32. id: 0,
  33. sname: '---',
  34. gender: false
  35. }
  36. }
  37. }
  38. }
  39. }
  40. const server = new ApolloServer({
  41. typeDefs,
  42. resolvers
  43. })
  44. const app = express()
  45. server.applyMiddleware({ app })
  46. app.listen(3001, () => {
  47. console.log("server is running");
  48. })
  49. // @include(id: Boolean) 仅在参数为true的时候,包含此字段
  50. // @skip(if: Boolean) 如果参数为true,跳过此字段
  51. // query directive($id: Int, $gender: Boolean!) {
  52. // stu(id: $id) {
  53. // id
  54. // sname
  55. // gender @include(if: $gender)
  56. // }
  57. // }
  58. // {
  59. // "id": 1,
  60. // "gender": false
  61. // }

枚举

  1. const express = require('express');
  2. const { ApolloServer, gql } = require('apollo-server-express');
  3. const typeDefs = gql`
  4. enum Favour {
  5. SWIMMING
  6. CODEING
  7. }
  8. type Query {
  9. hello: String
  10. info: Favour
  11. }
  12. `;
  13. const resolvers = {
  14. Query: {
  15. hello: () => 'Hello world!',
  16. info: () => {
  17. // 只能返回枚举中定义的那些值
  18. return 'SWIMMING'
  19. }
  20. },
  21. };
  22. const server = new ApolloServer({ typeDefs, resolvers });
  23. const app = express();
  24. server.applyMiddleware({ app });
  25. app.listen({ port: 3000 }, () =>
  26. console.log('Now browse to http://localhost:3000' + server.graphqlPath)
  27. );

parent

  1. const express = require('express')
  2. const { ApolloServer, gql } = require('apollo-server-express')
  3. const typeDefs = gql`
  4. type Student {
  5. sname: String
  6. age: Int
  7. favour: String
  8. }
  9. # 查询类型
  10. type Query {
  11. hello: String
  12. stu: Student
  13. }
  14. `
  15. const resolvers = {
  16. Student: {
  17. sname: (parent) => {
  18. // 这个时候 parent 参数才有用
  19. console.log(parent);
  20. return "zhangsan"
  21. },
  22. favour: (parent) => {
  23. // 可以对父节点传入的数据进行一些加工处理
  24. if (parent.favour == 'SWIMMING') {
  25. return '游泳'
  26. } else {
  27. return parent.favour
  28. }
  29. }
  30. },
  31. Query: {
  32. hello: () => 'hello world',
  33. // 对于根节点来说,parent参数没有用
  34. // context: 用于获取数据源对象
  35. stu: (parent, args, context) => {
  36. console.log(context.db)
  37. return {
  38. // 获取sname,获取的是 zhangsan
  39. sname: "张三"
  40. }
  41. }
  42. }
  43. }
  44. const context = () => {
  45. return {
  46. db: 'dbData'
  47. }
  48. }
  49. const server = new ApolloServer({
  50. typeDefs,
  51. resolvers,
  52. context
  53. })
  54. const app = express()
  55. server.applyMiddleware({ app })
  56. app.listen(3001, () => {
  57. console.log("server is running");
  58. })

变量

  1. // 变量的使用
  2. // 变量类型必须是标量
  3. // 变量可以有默认值 ($id: Int = 1)
  4. const express = require('express')
  5. const { ApolloServer, gql } = require('apollo-server-express')
  6. const typeDefs = gql`
  7. # 课程类型
  8. type Course {
  9. cname: String
  10. score: Float
  11. }
  12. # 学生类型
  13. type Student {
  14. id: Int
  15. sname: String
  16. age: Int
  17. scores(num: Float): [Course]
  18. }
  19. # 查询类型
  20. type Query {
  21. hello: String
  22. stu(id: Int): Student
  23. }
  24. `
  25. const resolvers = {
  26. Student: {
  27. scores: (parent, args) => {
  28. return parent.scores && parent.scores.filter(item => {
  29. return item.score > args.num
  30. })
  31. }
  32. },
  33. Query: {
  34. hello: () => "Hello World",
  35. stu: (parent, args) => {
  36. if (args.id == 1) {
  37. return {
  38. id: 1,
  39. sname: '张三',
  40. scores: [
  41. {
  42. cname: '数学',
  43. score: 99.5
  44. },
  45. {
  46. cname: '英语',
  47. score: 98.5
  48. }
  49. ]
  50. }
  51. } else {
  52. return {
  53. id: 0,
  54. sname: '---',
  55. score: null
  56. }
  57. }
  58. }
  59. }
  60. }
  61. const server = new ApolloServer({
  62. typeDefs,
  63. resolvers
  64. })
  65. const app = express()
  66. server.applyMiddleware({ app })
  67. app.listen(3001, () => {
  68. console.log("server is running");
  69. })
  70. // 多字段 参数传递
  71. // query param($id: Int, $num: Float) {
  72. // stu(id: $id) {
  73. // sname
  74. // scores(num: $num) {
  75. // cname
  76. // score
  77. // }
  78. // }
  79. // }
  80. // {
  81. // "id": 1,
  82. // "num": 95
  83. // }