当后端禁止 Mutation 批处理时,如何在链路层拆分请求?
解读
国内很多团队把 GraphQL 当作“聚合层”而非“网关层”,为了降低后端幂等复杂度或避免分布式事务,后端会直接关闭 Apollo Server 的 allowBatchedHttpRequests,甚至把 Content-Type: application/json 的数组格式当成 400 拦截。此时如果前端业务仍需要“一次用户操作触发多个 Mutation”(如创建订单同时扣减库存、写日志、发消息),就必须在链路层(即 Apollo Client 到 Server 的 HTTP 通道)把“逻辑批处理”拆成“物理单请求”,并保证:
- 失败回滚策略可落地(国内常用补偿事务而非原生 GraphQL 事务)
- 不破坏 React/Vue 组件的声明式写法
- 网络层面仍可利用浏览器并发上限(Chrome 同域 6~10)做并行加速
- 对上层业务代码透明,即组件层面仍写一次
useMutation,链路层自动拆分
知识点
- Apollo Link 体系:
apollo-link-split、apollo-link-serialize、apollo-link-batch-http的负向应用 - 操作类型识别:
operation.query.definitions[0].kind === 'OperationDefinition' && operation.query.definitions[0].operation === 'mutation' - 数组扁平化与请求编号:为每个 Mutation 生成唯一
requestId,后端返回时按extensions.requestId回包,前端重新聚合 - 错误隔离:单个 Mutation 4xx/5xx 不阻断其余请求,通过
onErrorLink 做补偿 - 并发控制:使用
p-limit或Promise.allSettled控制同域并发数,避免一次性打满连接池 - 幂等键透传:国内常用
Idempotency-Key头,链路层自动把原始 batch 的uuid透传给每个子请求,方便后端做幂等 - 缓存回写:拆分后每个 Mutation 返回的数据需要写回同一条缓存键,需手动调用
cache.writeFragment保证 UI 同步
答案
实现一个自定义 Apollo Link——SplitMutationLink,放在 BatchHttpLink 之前。伪代码如下:
import { ApolloLink, Observable } from '@apollo/client/core';
import { print } from 'graphql';
import { v4 as uuid } from 'uuid';
import pLimit from 'p-limit';
const limit = pLimit(6); // 同域并发上限
export const splitMutationLink = new ApolloLink((operation, forward) => {
// 只拦截 Mutation
const isMutation = operation.query.definitions.some(
(d: any) => d.kind === 'OperationDefinition' && d.operation === 'mutation'
);
if (!isMutation) return forward(operation);
// 把原始 batch 请求体拆成单条
const requests = operation.getContext().requests as any[] || [{ query: operation.query, variables: operation.variables }];
const batchId = uuid();
return new Observable(observer => {
Promise.allSettled(
requests.map((req, idx) =>
limit(async () => {
const singleOp = {
...operation,
query: req.query,
variables: req.variables,
setContext: (ctx: any) => ({
...ctx,
headers: {
...ctx.headers,
'Idempotency-Key': `${batchId}-${idx}`
}
})
};
return forward(singleOp).toPromise();
})
)
).then(results => {
const errors = results.filter(r => r.status === 'rejected').map((r: any) => r.reason);
const successes = results.filter(r => r.status === 'fulfilled').map((r: any) => r.value);
if (errors.length && successes.length) {
// 部分成功:走补偿
observer.error(new Error('PARTIAL_MUTATION_FAILURE'));
} else if (errors.length && !successes.length) {
observer.error(errors[0]);
} else {
// 全部成功,把数据重新组装成数组格式,供 UI 层消费
observer.next({ data: successes.map(s => s.data) });
observer.complete();
}
});
});
});
在 Client 初始化时:
const client = new ApolloClient({
link: ApolloLink.from([
splitMutationLink,
new BatchHttpLink({ uri: '/graphql' })
]),
cache
});
这样组件层仍写:
const [createOrder] = useMutation(CREATE_ORDER_MUTATION);
链路层自动把请求拆成单发,满足后端“禁止批处理”的硬性规定。
拓展思考
- 如果后端要求“顺序执行”而非“并发”,可把
pLimit(1)改成串行队列,并在extensions里带sequenceNumber,后端按序号执行 - 大文件场景(如上传合同、发票)可把 Mutation 拆成
@defer流式请求,利用@apollo/link-upload做分片,链路层再合并进度回调 - 低代码平台常见“批量审批”场景,前端用
useMutation一次性传 100 条 ID,链路层可拆成 5 组滑动窗口,失败组自动重试 3 次,成功组先刷新本地缓存,减少用户等待 - 监控:在
SplitMutationLink里埋点,把batchId、拆分数量、耗时、错误码打到阿里云 SLS 或腾讯云 CLS,方便后端做“伪批处理”性能调优 - 合规:金融场景下,链路层需把每个子请求的报文和响应做 SM4 加密并落本地 IndexedDB,审计时可直接回放,避免“批处理”日志缺失导致监管问询