【问题标题】:how to get return values from promise returned from AWS Auth.currentSession()如何从 AWS Auth.currentSession() 返回的 Promise 中获取返回值
【发布时间】:2021-08-08 07:33:52
【问题描述】:

我正在尝试从我可以从 AWS 获得的 jwt 令牌创建一个 graphql 客户端。

我想要的:在 var ListfulClient 中定义的 apollo 客户端对象

listfulClient ApolloClient {
  "cache": InMemoryCache {
    "addTypename": true,
    "config": Object {
      "addTypename": true,
      "dataIdFromObject": [Function defaultDataIdFromObject],
      "resultCaching": true,
      "typePolicies": Object {},
    },
    "data": Root {
      "canRead": [Function anonymous],
      "data": Object {},

我得到的:一个承诺

listfulClient Promise {
  "_U": 0,
  "_V": 0,
  "_W": null,
  "_X": null,
}

aws amplify 库中的函数Auth.currentSession() 似乎返回了一个承诺。但是,我似乎无法解析该值来制作我需要的 apollo 客户端。我尝试将我的函数gqlClient 设为异步函数,但当我尝试在 gqlClient 中使用它时,我收到错误 Unexpected reserved word 'await'.,即使我将函数设为异步也是如此。 你能帮帮我吗?我已经为此苦苦挣扎了几个小时


function gqlClient() {
  // return the promise from currentSession and
  // return the client with token data if
  // the user is logged in
  return Auth.currentSession().then(function(data) {
    // Set the appropriate headers for the environment
    const jwt = data.accessToken.jwtToken;
    const headers = {};
    const authLink = setContext((_, { headers }) => ({
      headers: {
        ...headers,
        authorization: jwt ? `Bearer ${jwt}` : "",
      },
    }));
    const httpLink = createHttpLink({
      uri: 'http://localhost:8080/query',
    });
    return new ApolloClient({
      connectToDevTools: true,
      link: authLink.concat(httpLink),
      cache: new InMemoryCache(),
    });
  })
  .catch(function(err){
    // something def went wrong
    console.log(err);
    return new ApolloClient({cache: new InMemoryCache(),});
  });
};

我想创建 apollo 客户端,它将在我的 react 组件中使用

function App() {
  // retrieve current session
  var ListfulClient = gqlClient();
  console.log("listfulClient", ListfulClient)
  let [fontsLoaded] = useFonts({
    Arimo_400Regular,
    Arimo_400Regular_Italic,
    Arimo_700Bold,
    Arimo_700Bold_Italic,
  });
  if (!fontsLoaded) {
    return <AppLoading />;
  } else {
    return (
      <ApolloProvider client={ListfulClient}>
        <NavigationContainer>
          <Stack.Navigator>
            <Stack.Screen name="Listful" options={{ headerShown: false }} component={HomeTabs} />
            <Stack.Screen name="Settings" component={SettingsScreen} />
          </Stack.Navigator>
        </NavigationContainer>
      </ApolloProvider>
    );
  }
}

【问题讨论】:

    标签: javascript react-native apollo-client


    【解决方案1】:

    你将不得不做这样的事情, 使用异步函数进行身份验证链接并从那里传递令牌。并通过链接将其传递给客户。

    const httpLink = createHttpLink({
      uri: 'http://localhost:8080/query',
    });
    
    const authLink = setContext(async (_, { headers }) => {
      const data = await Auth.currentSession();
      const jwt = data.accessToken.jwtToken;
      return {
        headers: {
          ...headers,
           authorization: jwt ? `Bearer ${jwt}` : "",
        },
      };
    });
    
    const client=new ApolloClient({
      connectToDevTools: true,
      link: authLink.concat(httpLink),
      cache: new InMemoryCache(),
    });
    

    在 App.js 中

    var ListfulClient = client;
    

    这将确保令牌在每个请求中都传递。

    【讨论】:

    • 这成功了!你能解释一下这部分代码吗,我不知道这里发生了什么:const authLink = setContext(async (_, { headers }) =&gt; {
    • 所以基本上这将调用一个异步函数,该函数将是每次从客户端发送请求时调用您的 getAuth 的函数。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多