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

Apollo Client 3中如何传递查询未预设的额外变量?

在Apollo Client 3中传递查询未定义的额外变量

Apollo Client 3会自动过滤掉查询文档中未声明的变量,因此直接在useQuery的variables参数中传入未定义的变量不会被发送到后端。以下是两种可行的解决方案:

方案一:自定义HTTP Link的请求处理逻辑

通过修改createHttpLink的fetch函数,在请求发送前将额外变量合并到请求体中:

import { ApolloClient, InMemoryCache, createHttpLink } from '@apollo/client';
import { setContext } from '@apollo/client/link/context';

// 定义HTTP链路,自定义fetch逻辑
const httpLink = createHttpLink({
  uri: '/api/graphql', // 替换为你的GraphQL端点
  fetch: async (uri, options) => {
    const { extraVariables, ...restOptions } = options as any;
    if (extraVariables) {
      // 解析原始请求体,合并额外变量
      const body = JSON.parse(restOptions.body as string);
      body.variables = { ...body.variables, ...extraVariables };
      restOptions.body = JSON.stringify(body);
    }
    return fetch(uri, restOptions);
  },
});

// 通过setContext传递额外变量到请求上下文
const contextLink = setContext((_, { headers, extraVariables }) => ({
  headers,
  extraVariables,
}));

// 创建Apollo Client实例
const client = new ApolloClient({
  link: contextLink.concat(httpLink),
  cache: new InMemoryCache(),
});

在调用useQuery时,通过context参数传递额外变量:

const responseData = useQuery<any, any>(queryHere, {
  client,
  context: {
    extraVariables: { data: { data1: '01', data2: '02', data3: '03' } },
  },
});

方案二:自定义Apollo Link拦截请求

创建一个自定义链路,拦截GraphQL操作并合并额外变量:

import { ApolloLink, Operation, NextLink } from '@apollo/client';
import { ApolloClient, InMemoryCache, createHttpLink } from '@apollo/client';

// 自定义链路:合并额外变量到操作的variables中
const extraVariablesLink = new ApolloLink((operation: Operation, forward: NextLink) => {
  const { extraVariables } = operation.getContext();
  if (extraVariables) {
    operation.setVariables({
      ...operation.variables,
      ...extraVariables,
    });
  }
  return forward(operation);
});

const httpLink = createHttpLink({
  uri: '/api/graphql', // 替换为你的GraphQL端点
});

// 创建Apollo Client实例
const client = new ApolloClient({
  link: extraVariablesLink.concat(httpLink),
  cache: new InMemoryCache(),
});

调用useQuery时同样通过context传递额外变量:

const responseData = useQuery<any, any>(queryHere, {
  client,
  context: {
    extraVariables: { data: { data1: '01', data2: '02', data3: '03' } },
  },
});

这两种方案都能绕过Apollo Client 3的变量校验,将未在查询中定义的额外变量发送到后端,适合用于用户验证等场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 08:12:49