Loading...
Loading...
Compare original and translation side by side
| Factor | Use GraphQL | Use REST |
|---|---|---|
| Client types | Multiple clients with different needs | Single client with predictable needs |
| Data relationships | Highly nested, interconnected data | Flat resources with few relationships |
| Over-fetching | Clients need different subsets | Clients typically need all fields |
| Under-fetching | Avoid multiple round trips | Single endpoint provides enough |
| Schema evolution | Frequent changes, backward compat | Stable API, versioning acceptable |
| Real-time | Subscriptions needed | Polling or webhooks sufficient |
| 考量因素 | 选择GraphQL | 选择REST |
|---|---|---|
| 客户端类型 | 多客户端且需求各异 | 单一客户端且需求可预测 |
| 数据关系 | 高度嵌套、相互关联的数据 | 扁平化资源且关联较少 |
| 过度获取 | 客户端需要不同的数据子集 | 客户端通常需要全部字段 |
| 获取不足 | 避免多次请求往返 | 单个端点即可满足需求 |
| Schema演进 | 频繁变更且需向后兼容 | API稳定,版本化可接受 |
| 实时性 | 需要订阅功能 | 轮询或WebHook即可满足 |
Schema Design Requirements
│
├─ Single service (monolith)?
│ └─ Schema-first design with single schema
│
├─ Multiple microservices?
│ ├─ Services owned by different teams?
│ │ └─ Apollo Federation
│ └─ Services owned by same team?
│ └─ Schema stitching (simpler)
│
├─ Existing REST APIs to wrap?
│ └─ GraphQL wrapper layer
│
└─ Need backward compatibility?
└─ Hybrid REST + GraphQLSchema设计需求
│
├─ 单一服务(单体应用)?
│ └─ 采用Schema优先设计,使用单一Schema
│
├─ 多微服务?
│ ├─ 服务由不同团队维护?
│ │ └─ 使用Apollo Federation
│ └─ 服务由同一团队维护?
│ └─ 使用Schema Stitching(更简单)
│
├─ 已有REST API需要封装?
│ └─ 搭建GraphQL封装层
│
└─ 需要向后兼容性?
└─ 采用REST+GraphQL混合架构Resolver Implementation
│
├─ Field resolves to single related entity?
│ └─ DataLoader with batching
│
├─ Field resolves to list of related entities?
│ ├─ List size always small (<10)?
│ │ └─ Direct query acceptable
│ └─ List size unbounded?
│ └─ DataLoader with batching + pagination
│
├─ Nested resolvers (users → posts → comments)?
│ └─ Multi-level DataLoaders
│
└─ Aggregations or counts?
└─ Separate DataLoader for counts解析器实现
│
├─ 字段关联单个实体?
│ └─ 使用DataLoader实现批量查询
│
├─ 字段关联实体列表?
│ ├─ 列表规模始终较小(<10条)?
│ │ └─ 直接查询即可
│ └─ 列表规模无上限?
│ └─ 结合DataLoader批量查询与分页
│
├─ 嵌套解析器(用户 → 帖子 → 评论)?
│ └─ 多层级DataLoader
│
└─ 需要聚合或计数?
└─ 为计数单独配置DataLoader// WITHOUT DataLoader - N+1 problem
const resolvers = {
Post: {
author: async (post, _, { db }) => {
// Executed once per post (N+1 problem!)
return db.User.findByPk(post.userId);
}
}
};
// Query for 100 posts triggers 101 DB queriesimport DataLoader from 'dataloader';
// Create loader per request (important!)
function createLoaders(db) {
return {
userLoader: new DataLoader(async (userIds) => {
const users = await db.User.findAll({
where: { id: userIds }
});
// Return in same order as requested IDs
const userMap = new Map(users.map(u => [u.id, u]));
return userIds.map(id => userMap.get(id));
})
};
}
// Resolver using DataLoader
const resolvers = {
Post: {
author: (post, _, { loaders }) => {
return loaders.userLoader.load(post.userId);
}
}
};
// Same query now triggers 2 queries total!// 未使用DataLoader - 存在N+1问题
const resolvers = {
Post: {
author: async (post, _, { db }) => {
// 每个帖子执行一次查询(N+1问题!)
return db.User.findByPk(post.userId);
}
}
};
// 查询100条帖子会触发101次数据库查询import DataLoader from 'dataloader';
// 每个请求创建独立的Loader(很重要!)
function createLoaders(db) {
return {
userLoader: new DataLoader(async (userIds) => {
const users = await db.User.findAll({
where: { id: userIds }
});
// 按照请求ID的顺序返回结果
const userMap = new Map(users.map(u => [u.id, u]));
return userIds.map(id => userMap.get(id));
})
};
}
// 使用DataLoader的解析器
const resolvers = {
Post: {
author: (post, _, { loaders }) => {
return loaders.userLoader.load(post.userId);
}
}
};
// 相同查询现在仅触发2次数据库查询!type Query {
users(first: Int, after: String, last: Int, before: String): UserConnection!
}
type UserConnection {
edges: [UserEdge!]!
pageInfo: PageInfo!
totalCount: Int!
}
type UserEdge {
node: User!
cursor: String!
}
type PageInfo {
hasNextPage: Boolean!
hasPreviousPage: Boolean!
startCursor: String
endCursor: String
}type Query {
users(first: Int, after: String, last: Int, before: String): UserConnection!
}
type UserConnection {
edges: [UserEdge!]!
pageInfo: PageInfo!
totalCount: Int!
}
type UserEdge {
node: User!
cursor: String!
}
type PageInfo {
hasNextPage: Boolean!
hasPreviousPage: Boolean!
startCursor: String
endCursor: String
}type Mutation {
createUser(input: CreateUserInput!): CreateUserPayload!
}
type CreateUserPayload {
user: User
errors: [UserError!]!
}
type UserError {
field: String
message: String!
code: ErrorCode!
}
enum ErrorCode {
VALIDATION_ERROR
NOT_FOUND
UNAUTHORIZED
CONFLICT
}type Mutation {
createUser(input: CreateUserInput!): CreateUserPayload!
}
type CreateUserPayload {
user: User
errors: [UserError!]!
}
type UserError {
field: String
message: String!
code: ErrorCode!
}
enum ErrorCode {
VALIDATION_ERROR
NOT_FOUND
UNAUTHORIZED
CONFLICT
}| Observation | Why Escalate |
|---|---|
| Query complexity explosion | Unbounded nested queries causing DoS |
| Federation circular dependencies | Schema design issue |
| 10K+ concurrent subscriptions | Infrastructure architecture |
| Schema versioning across 50+ fields | Breaking change management |
| Cross-service transaction needs | Distributed systems pattern |
| 现象 | 升级原因 |
|---|---|
| 查询复杂度急剧上升 | 无限制的嵌套查询可能导致拒绝服务(DoS) |
| 联邦架构出现循环依赖 | Schema设计存在问题 |
| 并发订阅数超过10000 | 涉及基础设施架构调整 |
| Schema版本变更涉及50+字段 | 需处理破坏性变更管理 |
| 跨服务事务需求 | 涉及分布式系统模式设计 |