Mutation 幂等性保证:基于客户端生成的Idempotency Key
防止重复支付/创建操作,实现幂等Mutation中间件。 · 难度:入门 · +10XP
幂等键与副作用控制
网络重试可能导致关键Mutation执行多次。本教程将实现幂等模式:客户端在Mutation请求头中携带唯一键(例如UUID),服务端缓存首次执行结果并直接返回给后续相同键的请求。深入探讨存储策略(内存/Redis)、过期时间以及如何与数据库事务原子结合。
function idempotentMiddleware(resolver) {
return async (parent, args, ctx, info) => {
const key = ctx.req.headers['idempotency-key'];
if (!key) return resolver(parent, args, ctx, info);
const cached = await ctx.cache.get(key);
if (cached) return JSON.parse(cached);
const result = await resolver(parent, args, ctx, info);
await ctx.cache.set(key, JSON.stringify(result), 'EX', 3600);
return result;
};
}