4

So I followed the documentation from this post to implement the refresh token logic How to refresh JWT token using Apollo and GraphQL

Here's my code:

import Auth from '@aws-amplify/auth';
const getNewToken = () => {
  return Auth.currentSession()
    .then(data => {
      return {
        accessToken: data.getAccessToken().getJwtToken(),
        refreshToken: data.getRefreshToken().getToken()
      };
    })
    .catch(error => {
      console.log('error', error);
    });
};
const link = ApolloLink.from([
  stateLink,
  authLink,
  onError(({ graphQLErrors, networkError, operation, forward }) => {
    if (graphQLErrors) {
      graphQLErrors.map(({ message, locations, path, extensions }) => {
        if (message.includes('Access Token has expired')) {
          console.log('access token has expired');
          return fromPromise(
            getNewToken().catch(error => {
              console.log('error', error)
              // Handle token refresh errors e.g clear stored tokens, redirect to login
            })
          )
            .filter(value => Boolean(value))
            .flatMap(accessToken => {
              console.log('access token!!!', accessToken)
              const oldHeaders = operation.getContext().headers;
              // modify the operation context with a new token
              operation.setContext({
                headers: {
                  ...oldHeaders,
                  authorization: `Bearer ${accessToken}`
                }
              });
              // retry the request, returning the new observable
              return forward(operation);
            });
        }
        console.log(
          `[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`
        );
      });
    }
    if (networkError) console.log(`[Network error]: ${networkError}`);
  }),
  linkHttp
]);

But it does not work, the request is not made again and even the console.log('access token!!!', accessToken) is not being called.I don't know why the code inside flatMap() is not being executed. I can't figure out what am I doing wrong, please advise what should I do

0 Answers0