You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

urql执行mutation前如何全局移除查询结果中的__typename字段?

urql全局移除mutation变量中__typename字段的实现方案

urql支持两种全局处理方案,无需在每个useMutation调用前手动删除字段:

方案1:自定义Exchange全局拦截(通用方案,适配所有urql配置场景)

urql的Exchange功能等价于Apollo的ApolloLink,可全局拦截所有向外发送的请求,统一处理请求变量:

  1. 先实现递归移除__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
}
  1. 实现自定义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
    })
  )
}
  1. 注册到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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.20 05:06:04