react-native - 如何配置 Amplify 以使用多个 AppSync 端点?

标签 react-native apollo-client aws-appsync aws-amplify

我需要在 React Native 应用程序中支持经过身份验证和未经身份验证的 AppSync 请求。由于 AppSync 只允许每个 API 使用一种授权类型,因此我设置了两种 API:一种用于经过身份验证的用户(Cognito 用户池),一种用于访客(API key )。

我认为要完成这项工作,我需要有两个不同的 AWSAppSyncClient配置在同一个应用程序中。

  // authenticated user    
  const appSyncAuthenticatedClient = new AWSAppSyncClient({
    url: Config.APPSYNC_AUTHENTICATED_ENDPOINT,
    region: Config.APPSYNC_REGION,
    auth: {
      type: 'AMAZON_COGNITO_USER_POOLS',
      jwtToken: async () =>
        (await Auth.currentSession()).getAccessToken().getJwtToken()
    }
  });

  // guest    
  const appSyncUnauthenticatedClient = new AWSAppSyncClient({
    url: Config.APPSYNC_UNAUTHENTICATED_ENDPOINT,
    region: Config.APPSYNC_REGION,
    auth: {
      type: 'API_KEY',
      apiKey: Config.APPSYNC_API_ID
    }
  });

然后根据他们是否登录来决定使用哪个
    Auth.currentAuthenticatedUser()
      .then(user => this.appSyncRunningClient = appSyncAuthenticatedClient)
      .catch(err => this.appSyncRunningClient = appSyncUnauthenticatedClient);

    const App = props => {
      return (
        <ApolloProvider client={this.appSyncRunningClient}>
          <Rehydrated>
              <RootStack/>
            </Root>
          </Rehydrated>
        </ApolloProvider>
      );
    };

    export default App;

这失败了,因为 currentAuthenticatedUser返回一个 promise ,我被困在如何在应用程序的这个顶级实例化中解决一个 promise 。我还需要在身份验证事件期间更换此配置。

我可以通过什么方式动态选择和更改 ApolloProvider在启动和身份验证事件中配置?

最佳答案

这是目前不可能的。在正式支持顶级 await 之前,您应该创建两个 Apollo 客户端,一个用于 API,另一个用于 Cognito。

例如:在你的 App.js 中

export default function App(props) {
  const [client, setClient] = useState(null);

  useEffect(() => {
   checkAuth()
  }, []);

  function checkAuth() {
    Auth.currentSession().then(session => {
      const token = session.getIdToken();
      const jwtToken = token.getJwtToken();
      if (typeof jwtToken == "string") {
        const authClientConfig = {
          url: awsmobile.aws_appsync_graphqlEndpoint,
          region: awsmobile.aws_appsync_region,
          disableOffline: true,
          auth: {
            type: AUTH_TYPE.AMAZON_COGNITO_USER_POOLS,
            jwtToken: jwtToken
          }
        }
        const link = ApolloLink.from([createAuthLink(authClientConfig), createSubscriptionHandshakeLink(authClientConfig)]);
        const authClient = new ApolloClient({ link, cache: new InMemoryCache({ addTypename: false }) });
        setClient(authClient);
      } else {
        throw "error";
      }
    }).catch(e => {
      console.log(e);
      const config = {
        url: awsmobile.aws_appsync_graphqlEndpoint,
        region: awsmobile.aws_appsync_region,
        disableOffline: true,
        auth: {
          type: AUTH_TYPE.API_KEY,
          apiKey: awsmobile.aws_appsync_apiKey
        }
      }
      const link = ApolloLink.from([createAuthLink(config), createSubscriptionHandshakeLink(config)]);
      const authClient = new ApolloClient({ link, cache: new InMemoryCache({ addTypename: false }) });
        setClient(authClient);
    })
  }

    if (!client) {
      return "Loading..."
    }

    return (
      <ApolloProvider client={client}>
          ...
      </ApolloProvider>
    );
}`

关于react-native - 如何配置 Amplify 以使用多个 AppSync 端点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54273144/

相关文章:

reactjs - 如何在 react native 路由器通量中更改后退按钮箭头的颜色?

reactjs - 如何检测 FlatList 何时呈现所有项目并实际滚动到底部?

javascript - [GraphQL 错误] : Message: Unknown fragment

javascript - 与 AppSync 的 Websocket 连接 : ErrorCode 400 'NoProtocolError'

aws-lambda - AppSync 与 AWS4 和混合身份验证类型(用户池和 IAM)

android - 崩溃后的 react native 应用程序显示闪屏

ios - AsyncStorage 引用崩溃 react iOS 上的 native 应用程序

angular - 何时在 Apollo-Angular 中使用 watchQuery 或查询?

javascript - GraphQL 查询结构

amazon-web-services - FriendsList 的 AWS AppSync 用户关系