urql执行mutation前如何全局移除查询结果中的__typename字段?
urql全局移除mutation变量中__typename字段的实现方案
urql支持两种全局处理方案,无需在每个useMutation调用前手动删除字段:
方案1:自定义Exchange全局拦截(通用方案,适配所有urql配置场景)
urql的Exchange功能等价于Apollo的ApolloLink,可全局拦截所有向外发送的请求,统一处理请求变量:
- 先实现递归移除__typename的工具函数,覆盖嵌套对象、数组场景:
// 递归移除对象所有层级的__typename字段 const deepOmitTypename = (value: any): any => { if (Array.isArray(value)) { return value.map(deepOmitTypename) } if (typeof value === 'object' && value !== null) { const newObj = {} for (const key in value) { if (key !== '__typename') { newObj[key] = deepOmitTypename(value[key]) } } return newObj } return value }
- 实现自定义Exchange,放在请求发送链路的前置位:
import { createClient, fetchExchange, forward } from '@urql/core' const omitTypenameExchange = forward => operations => { return forward( operations.map(op => { // 可新增 op.kind === 'mutation' 条件,仅处理mutation请求降低开销 if (op.variables) { return { ...op, variables: deepOmitTypename(op.variables) } } return op }) ) }
- 注册到urql客户端的exchange数组中,注意放在
fetchExchange之前:
const client = createClient({ url: '/graphql', exchanges: [ // 其他内置exchange(如dedupExchange、cacheExchange)放在前面 omitTypenameExchange, fetchExchange ] })
方案2:GraphCache内置配置(适用于使用@urql/exchange-graphcache的项目)
如果项目采用了官方的GraphCache作为缓存方案,直接开启内置的omitTypename配置即可自动完成变量清洗:
import { cacheExchange } from '@urql/exchange-graphcache' const cache = cacheExchange({ omitTypename: true, // 开启后自动移除所有请求变量中的__typename字段 // 其余缓存配置 }) // 将cache注册到client的exchanges数组即可
两种方案均支持嵌套结构变量处理,完全替代手动执行
delete input.__typename的操作。
内容的提问来源于stack exchange,提问作者capiono
相关产品推荐
相关产品推荐

