简介

工作室的api接口方案采用graphql,前端只要求会写query,mutation语句即可

GraphQL 是一个用于 API 的查询语言,是一个使用基于类型系统来执行的查询规范,可以类比于sql,只不过查询对象由数据库变为了后台服务器

具体可看官方文档:https://graphql.cn/learn/

要点

graphql有三个要点,type,query,mutation
举例:

  1. type User {
  2. id: ID
  3. }
  4. type Query {
  5. user(
  6. id: ID
  7. ): User!
  8. ... 可以多个query函数
  9. }
  10. type Mutation {
  11. user: User
  12. ... 可以多个mutation函数
  13. }

如何学习

看文档固然重要,但是缺少恰当的练习,也很难掌握一个新知识,所以我们需要配合graphql-faker工具进行练习

graphql-faker地址:https://github.com/APIs-guru/graphql-faker

  1. npm install -g graphql-faker // 如果安装失败,需要管理员权限窗口
  2. graphql-faker --open // 之后会打开一个本地graphql服务,http://localhost:9002/editor/
  1. 选择第二个

image.png

  1. 选择查看右边的docs,可以看到只有query存在,那是因为shcema中只定义了query。

image.pngimage.png

  1. 尝试第一个query

image.pngimage.png
根据以上两个文档可以写出
image.png
可以看到

  • 查询语句是根据文档上的query 函数写出的
  • 有参数要求的需要传递参数,点击 query variables可以打开定义区
  • 查询结果和查询语句结构差不多

还可以看到,由于查询语句只传了id, 所以只返回了employee的id字段,可以看到文档上employee不止这一个字段,还有company等等等等,尝试修改查询语句,你可以任意得到自己想要的字段

如果不带参数的query,会比较简单

image.png

  1. docs文档是联系graphql的关键

整个的docs结构如下:

graphql入门 - 图8其中订阅类型暂不需要掌握,那这个docs怎么产生呢,答案是schema文档定义的

image.png

可以看到,所有的类型和查询定义都在这个文档里,这个文档比较简单,需要测试更多语句可以用下方的文档覆盖原本的,点击save保存,就可以开始新的尝试了。

  1. type Company {
  2. name: String @fake(type:companyName)
  3. industry: String @examples(values: ["IT", "Manufacturing", "Medicine", "Media"])
  4. employees: [Employee!]
  5. }
  6. # Employee type
  7. type Employee {
  8. firstName: String @fake(type: firstName, locale:en_CA)
  9. lastName: String @fake(type: lastName, locale:en_CA)
  10. address: String @fake(type:streetAddress, options: { useFullAddress: true })
  11. subordinates: [Employee!]!
  12. company: Company
  13. }
  14. interface Node {
  15. id: ID!
  16. }
  17. interface Character {
  18. id: ID!
  19. name: String!
  20. }
  21. type Human implements Character, Node {
  22. id: ID!
  23. name: String!
  24. totalCredits: Int
  25. }
  26. union UNIONMASTER = Employee | User | Company
  27. enum Role {
  28. # Adimn role
  29. ADMIN
  30. USER @deprecated(reason: "not cool")
  31. # Jedi
  32. JEDI
  33. NO_DESCRIPTION
  34. DEP_NO_REASON @deprecated
  35. }
  36. type User {
  37. # User role lorem ipsum
  38. role: Role
  39. union: UNIONMASTER
  40. dep: String @deprecated(reason: "hey")
  41. hey: String!
  42. id: ID
  43. }
  44. type Query {
  45. # get first user
  46. user(
  47. # Hey i am the id
  48. id: ID
  49. ): User!
  50. human: Human
  51. employee(id: ID, name: String, lorem: String, Ipsum: Int): Employee
  52. company(id: ID): Company
  53. allCompanies: [Company!]
  54. }
  55. type Mutation {
  56. user: User
  57. }