能否将BatchHttpLink Apollo返回的multipart/mixed内容与graphql-codegen hooks结合?
解决BatchHttpLink处理multipart/mixed响应时useQuery data返回undefined的问题
问题根源
BatchHttpLink 默认不会自动解析 multipart/mixed 格式的批量响应,导致 Apollo Client 无法正确提取数据映射到 useQuery 的 data 字段。
解决方案:自定义响应解析器
你需要在 BatchHttpLink 的配置中添加自定义的 parseResponse 函数,手动处理 multipart 响应的拆分与解析:
步骤1:实现multipart响应解析逻辑
先写一个工具函数拆分multipart响应并解析每个部分的JSON:
function parseMultipartResponse(response) { // 从响应头提取boundary分隔符 const contentType = response.headers.get('Content-Type'); const boundaryMatch = contentType.match(/boundary=(.+)/); if (!boundaryMatch) return null; const boundary = `--${boundaryMatch[1]}`; return response.text().then(text => { // 拆分响应内容,过滤无效项 const parts = text.split(boundary).filter(part => part.trim() && !part.includes('--')); // 解析每个部分为JSON对象 return parts.map(part => { // 跳过每个部分的头部信息,提取JSON内容 const jsonPart = part.split('\r\n\r\n')[1]; return JSON.parse(jsonPart); }); }); }
步骤2:配置BatchHttpLink时注入自定义解析器
创建BatchHttpLink时传入parseResponse选项,针对multipart格式做特殊处理:
import { BatchHttpLink } from '@apollo/client/link/batch-http'; const batchLink = new BatchHttpLink({ uri: '/graphql/batch', parseResponse: async (response, options) => { const contentType = response.headers.get('Content-Type'); // 判断响应是否为multipart/mixed格式 if (contentType?.includes('multipart/mixed')) { const parsedParts = await parseMultipartResponse(response); // 返回解析后的结果数组,对应批量查询的每个请求结果 return parsedParts; } // 非multipart格式沿用默认JSON解析逻辑 return response.json(); }, });
步骤3:集成到Apollo Client
将配置好的batchLink加入客户端的link链中:
import { ApolloClient, InMemoryCache, from } from '@apollo/client'; const client = new ApolloClient({ link: from([batchLink]), // 可与authLink等其他链路组合使用 cache: new InMemoryCache(), });
验证要点
- 确认后端返回的
multipart/mixed响应格式合规,每个分片都是有效的GraphQL响应(包含data或errors字段) - 测试批量查询时,useQuery的
data字段应能正确获取对应查询的返回结果
内容的提问来源于stack exchange,提问作者Anton Zinch3nko
相关产品推荐
相关产品推荐

