Apollo Client Error Link Retry operation after fetch request or mutation done

430 Views Asked by At

I want to refresh my jwt cookie whenever server send back unauthenticated error , because of the jwt cookie expired . After that error response come back to errorLink I want to send another mutation or fetch request to server for refresh auth cookie , then when that refresh requests response come back (fullfilled) to error link then retry the first query or mutation.I dont use token on local storage i just want to use http only cookie . Cokkie works fine but my problem is just refresh logic. I couldnt implement that. Any suggest or sample code about that problem ? Thank you.

i tried below for errorlink

  let tokenRefreshPromise = Promise.resolve();
  let isRefreshing;

  const errorLink = onError(
  ({
      graphQLErrors,
      networkError,
      operation,
      forward
  }) => {
      if (graphQLErrors) {
          console.log(graphQLErrors);
          graphQLErrors.forEach(({
              message,
              locations,
              path
          }) => {
              if (
                  message === "You do not have permission to perform this action" &&
                  !isRefreshing
              ) {
                  isRefreshing = true;
                  tokenRefreshPromise = fetch(process.env.REACT_APP_GRAPH_URL, {
                      method: "POST",
                      mode: "cors",
                      credentials: "include",
                      headers: {
                          "Content-Type": "application/json",
                      },
                      body: JSON.stringify({
                          query: `mutation{
                refreshToken {
                  payload
                  refreshExpiresIn
                }
              }`,
                      }),
                  });
                  // console.log(tokenRefreshPromise);
                  tokenRefreshPromise.then(() => (isRefreshing = false));
              }
              return fromPromise(tokenRefreshPromise).flatMap(() =>
                  forward(operation)
              );
          });
      }

      if (networkError) {
          console.log(`[Network error]: ${networkError}`);
      }
  }
 );
0

There are 0 best solutions below