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

如何在Apollo Client 3中统一过滤所有Mutation的Payload?

问题:如何为Apollo Client 3的所有Mutation统一应用输入过滤函数?

我想了解是否可通过插件、中间件等方式,为Apollo Client 3的每个Mutation应用过滤函数处理字符串。例如:

// In my schema
input Comment {
  status: "SENT",
  comment: String
}

mutation updateStatus($id: String, $input: Comment!) {
  updateStatus(id: $id, input: $input) 
}
// and I call the mutation from React
useMutation(UPDATE_STATUS, { options });

我有许多类似的带input参数的Mutation,希望用如下简单函数统一过滤每个输入:

// This will take each value of the input object and replace the strings that match with "some char"
const clearMutationPayload = (input) => Object.values(input).map(val => val.replace('some char', ''));

请问有可行方案吗?


解决方案

当然有可行方案,最直接的方式是利用Apollo Link创建中间件,拦截所有Mutation请求并统一处理输入参数:

步骤1:完善过滤函数

首先修正你的过滤函数,确保它能递归处理嵌套对象(如果input有多层结构),同时保留原对象的键值结构(原函数会丢失键,只返回值数组,不符合实际需求):

const clearMutationPayload = (input) => {
  if (typeof input !== 'object' || input === null) {
    // 非对象类型:如果是字符串就替换目标字符,否则返回原值
    return typeof input === 'string' ? input.replace('some char', '') : input;
  }
  // 遍历对象键值,递归处理每个属性
  return Object.fromEntries(
    Object.entries(input).map(([key, val]) => [key, clearMutationPayload(val)])
  );
};

步骤2:创建Mutation拦截中间件

通过Apollo Link拦截Mutation请求,修改其变量:

import { ApolloLink } from '@apollo/client';

const mutationFilterLink = new ApolloLink((operation, forward) => {
  // 只处理Mutation类型的请求
  if (operation.operationName === 'mutation') {
    // 复制原变量,避免修改原始数据
    const filteredVariables = { ...operation.variables };
    
    // 处理名为`input`的参数(如果你的输入参数命名不同,可调整逻辑)
    if (filteredVariables.input) {
      filteredVariables.input = clearMutationPayload(filteredVariables.input);
    }
    
    // 若要处理所有变量中的字符串,可替换为:
    // filteredVariables = clearMutationPayload(filteredVariables);
    
    // 更新操作的变量
    operation.setVariables(filteredVariables);
  }
  
  // 继续传递请求到下一个Link节点
  return forward(operation);
});

步骤3:将中间件加入Apollo Client的Link链

创建Apollo Client实例时,把自定义Link和HttpLink组合:

import { ApolloClient, InMemoryCache, HttpLink, from } from '@apollo/client';

const httpLink = new HttpLink({ uri: '你的GraphQL端点地址' });

// 自定义中间件要放在HttpLink前面,确保请求先被处理再发送
const link = from([mutationFilterLink, httpLink]);

const client = new ApolloClient({
  link,
  cache: new InMemoryCache(),
});

这样所有通过该Client发起的Mutation请求,输入参数都会被自动过滤处理,无需在每个useMutation调用中重复编写逻辑。


内容的提问来源于stack exchange,提问作者pmiranda

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 14:05:17