如何将自定义authenticatedFetch函数接入Apollo Client?
如何让Apollo Client使用Shopify App Bridge的authenticatedFetch发起GraphQL请求
完全可以实现,Apollo Client允许你替换默认的fetch实现,不管是GraphQL还是REST请求都能适配。下面是两种可行的方案:
方案一:修改HttpLink的fetch参数
这是最直接的方式,利用createHttpLink的fetch配置项传入你的authenticatedFetch函数:
import { ApolloClient, InMemoryCache, createHttpLink } from '@apollo/client'; import { authenticatedFetch } from '你的Shopify库路径'; // 创建自定义HttpLink,指定GraphQL端点和authenticatedFetch const httpLink = createHttpLink({ uri: '/api/graphql', // 你的Shopify GraphQL端点 fetch: authenticatedFetch, // 替换默认fetch为authenticatedFetch }); // 初始化Apollo Client const client = new ApolloClient({ link: httpLink, cache: new InMemoryCache(), });
Apollo Client会自动把GraphQL请求的query、variables等参数打包成符合要求的RequestInit对象(包括POST方法、JSON格式的body),直接传给authenticatedFetch处理,无需额外适配。
方案二:自定义ApolloLink(更灵活的控制)
如果需要在请求前后添加额外逻辑,可以自定义一个ApolloLink来调用authenticatedFetch:
import { ApolloClient, InMemoryCache, ApolloLink, Observable } from '@apollo/client'; import { authenticatedFetch } from '你的Shopify库路径'; const customAuthLink = new ApolloLink((operation, forward) => { return new Observable((observer) => { // 构建GraphQL请求的参数 const { query, variables, operationName } = operation; const requestOptions = { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ query, variables, operationName }), }; // 调用authenticatedFetch发起请求 authenticatedFetch('/api/graphql', requestOptions) .then(response => response.json()) .then(result => { // 将结果传递给下一个link(比如cache) observer.next(result); observer.complete(); }) .catch(error => { observer.error(error); }); }); }); // 初始化Apollo Client const client = new ApolloClient({ link: customAuthLink, cache: new InMemoryCache(), });
这种方式适合需要修改请求头、处理响应数据等自定义场景,完全掌控请求的生命周期。
注意事项
- 确保
authenticatedFetch能正确处理RequestInit中的body、headers等参数,Shopify的官方实现是支持标准HTTP请求配置的,所以无需担心兼容性。 - 如果你同时使用其他ApolloLink(比如errorLink),可以用
ApolloLink.from()组合多个link:const client = new ApolloClient({ link: ApolloLink.from([errorLink, customAuthLink]), cache: new InMemoryCache(), });
内容的提问来源于stack exchange,提问作者wwohlers
相关产品推荐
相关产品推荐

