介绍
使用 GraphQL 替代 RESTful 接口。
类似于传统的微服务架构及负载均衡架构,将 GraphQL 的模型定义(SDL)拆分成 SubGraph。
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-7QCQVsOZ-1657539190450)(https://cdn.nlark.com/yuque/__mermaid_v3/70df38234687b9975e932f993d52487f.svg)]
其中,包括以下核心组成部分:
- GraphQL API Gateway: 一个统一的请求入口
- SubGraph Services: 各业务模块,包括 SDL 及其对应的 Resolvers
各个服务的数据来源包括不限于:
- 各种语言实现的 RESTful API 接口
- 各种数据库、缓存,如 MongoDB、 Redis、 MySQL 等
同时,各个服务也可以通过 k8s 或者其他方式实现负载均衡。
技术方案
Apollo Federation
https://www.apollographql.com/docs/federation/
目前较为成熟的解决方案。
GraphQL Mesh
https://github.com/Urigo/graphql-mesh/
一种 0 代码的解决方案。支持的类型有:数据库、Swagger配置的接口、gRPC 服务(prototype)等。
该组织还提供了许多工具。
AWS AppSync
https://aws.amazon.com/cn/appsync/
云端版本的 GraphQL Mesh。
实施
后端
-
配置一个 Gateway
-
配置一个 SubGraph Service
-
- Code-First 或者 Schema-First 方式展开一个新的 GraphQL 服务
- Transform 某个 Open API 接口,或者对原有业务进行 GraphQL 的改造
-
扩展: 重复第 2 步骤
关注点:
- 数据类型
- 权限校验
- 性能提升
无需再关注业务,也无需为了 CRUD 增加新的接口。
前端
- 获取一个 GraphQL SDL 定义文件
- Mock 模拟数据进行前端开发
关注点:
- 网络请求优化
- 本地数据存储
- 交互体验
无需再关注接口数据格式,也无需进行反复的联调。
TBD.
Demo
-
Apollo Gateway
-
- Authorization
-
User Service
-
- Authentication
-
Resovation Service
问题整理
TypeScript 兼容性
- 类型:所有示例中,要么使用 any,要么没有申明类型(如 Resolver 函数)
- 返回值: 所有示例中,均未提供返回类型
解决方案:
- 关闭 Typescript 类型检查(不推荐),或者直接用 Node.js(目前尝试的方向)。
- TypeScript 类型处理参考: https://github.com/apollographql/apollo-server/issues/3666
嵌套分页:
typedef:
type User @key(fields: "id") {
id: ID!
username: String!
books(first: Int, after: String): Pagination
}
type Book {
name: String!
}
type Edges {
node: Node
cursor: String
}
type PageInfo {
endCursor: String
hasPrevPage: Boolean
hasNextPage: Boolean
}
type Pagination {
edges: [Edges]
totalCount: Int
pageInfo: PageInfo
}
union Node = User | Reservation | Book
query:
user(id: $userId) {
id
username
books(first: $booksFirst2, after: $booksAfter2) {
edges {
node {
... on Book {
name
}
}
cursor
}
totalCount
pageInfo {
endCursor
hasNextPage
}
}
}
response:
{
"data": {
"user": {
"id": "1",
"username": "willin",
"books": null
}
}
}
嵌套类型没有按预期进行分页,嵌套类型执行一次query还是对users和books分别进行query,并触发各自对应的resolver?
需要对GraphQL的原理进行深入了解。
ToDo List
-
Testing with mock
-
Authentication
-
- https://www.apollographql.com/docs/apollo-server/security/authentication/
-
Authorization
-
- https://www.apollographql.com/blog/backend/auth/setting-up-authentication-and-authorization-apollo-federation/