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

React Native项目中AWS Amplify关联Apollo Client的URI配置咨询

关联AWS Amplify与Apollo Client的配置方案

1. 获取正确的GraphQL端点URI

AWS Amplify配置GraphQL后会生成专属端点,你可以通过两种方式获取:

  • 查看项目根目录aws-exports.js文件中的aws_appsync_graphqlEndpoint字段,这就是需要的URI
  • 登录AWS控制台,进入AppSync服务找到对应项目的GraphQL端点地址

2. 配置带认证与本地缓存的Apollo Client

要获取登录用户信息,需将Amplify的认证令牌注入Apollo请求头,同时通过缓存实现本地存储。以下是React Native TypeScript的完整代码示例:

import { ApolloClient, InMemoryCache, createHttpLink } from '@apollo/client';
import { setContext } from '@apollo/client/link/context';
import { Amplify, Auth } from 'aws-amplify';
import awsconfig from './aws-exports';

// 初始化Amplify
Amplify.configure(awsconfig);

// 创建HTTP链接,使用Amplify提供的GraphQL端点
const httpLink = createHttpLink({
  uri: awsconfig.aws_appsync_graphqlEndpoint,
});

// 注入认证令牌到请求头
const authLink = setContext(async (_, { headers }) => {
  // 获取当前登录用户的会话令牌
  const session = await Auth.currentSession();
  const token = session.getIdToken().getJwtToken();

  return {
    headers: {
      ...headers,
      Authorization: token ? `Bearer ${token}` : '',
    },
  };
});

// 创建Apollo Client实例
const client = new ApolloClient({
  link: authLink.concat(httpLink),
  cache: new InMemoryCache({
    // 可选:配置用户数据的缓存策略
    typePolicies: {
      Query: {
        fields: {
          currentUser: {
            read(existing) {
              // 优先读取缓存数据
              return existing || null;
            },
          },
        },
      },
    },
  }),
});

export default client;

3. 持久化本地存储(可选)

默认的InMemoryCache在APP重启后会清空,若需持久化用户数据,可使用apollo3-cache-persist将缓存同步到React Native的AsyncStorage:

import { persistCache } from 'apollo3-cache-persist';
import AsyncStorage from '@react-native-async-storage/async-storage';

// 在创建client后初始化持久化缓存
persistCache({
  cache: client.cache,
  storage: AsyncStorage,
});

4. 查询登录用户信息示例

通过GraphQL查询获取当前用户信息,数据会自动存入Apollo本地缓存:

query GetCurrentUser {
  currentUser {
    id
    username
    email
  }
}

在组件中使用useQuery钩子调用该查询即可获取并缓存用户数据。

内容的提问来源于stack exchange,提问作者Jason Byron Beedle

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 22:57:25