apollo-link-token-refresh icon indicating copy to clipboard operation
apollo-link-token-refresh copied to clipboard

Use Apollo to fetch the fresh token

Open rvetrsek opened this issue 6 years ago • 6 comments

Hello,

I have a GraphQL mutation to refresh the token. Can I somehow use the mutation in the fetchAccessToken function?

rvetrsek avatar Sep 13 '19 14:09 rvetrsek

@obsessen did u get through with it?

jampack avatar Sep 15 '19 21:09 jampack

@akkhan20 unfortunately no. I'm still new to GraphQL and Apollo, so some help would be appreciated.

I think I know what my problem is. I'm trying to call an Apollo mutation in the fetchAccessToken function but the tokenRefreshLink catches this request as well and adds it to the "query waiting list"... Is there a way I can make this work?

rvetrsek avatar Sep 16 '19 04:09 rvetrsek

@obsessen @da3monHunter Have you tried something like this?

 fetchAccessToken: async () => {
  const resp = await fetch(environment.graphqlRemote, {
    method: 'POST',
    headers: {
      Authorization: `JWT ${currentAccessToken}`,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      query: `mutation RefreshToken { refreshToken(refreshToken: "${refreshToken}") { token refreshToken } }`
    })
  });
  return resp.json();
},
handleResponse: (operation, accessTokenField) => (response: RefreshReponse) => {
  console.log('handleResponse', response);
}

bartholomej avatar Oct 09 '19 12:10 bartholomej

const refreshTokenMutation = JSON.stringify({
  query: `mutation{
  refreshToken(data: {refresh_token: "${getRefreshToken()}"}){
    access_token
    refresh_token
    expires_in
  }
}`,
});
fetchAccessToken: async () => {
    const resp = await fetch(URI, {
      headers: { 'content-type': 'application/json' },
      method: 'POST',
      body: refreshTokenMutation,
    });
    return resp.json();
  },
  handleResponse: (operation, accessTokenField) => (response) => {
    console.log(response);
  },

jampack avatar Oct 20 '19 04:10 jampack

Accidentally found this.

I myself end up with the similar solution to refresh the access token using axios, with mutation query inside the axios request.

Haven't found the solution to use mutation inside ApolloClient onError link...

subotkevic avatar Feb 02 '20 18:02 subotkevic

Im getting a status 500 when fetchAccessToken gets executed...

 body: (...)
 bodyUsed: false
 headers: Headers {}
 ok: false
 redirected: false
 status: 500
 statusText: "Internal Server Error"
 type: "cors"
 url: "http://localhost:3000/graphql"

Any idea what could be happening?

fetch('http://localhost:3000/graphql', {
   method: 'POST',
   headers: { 'content-type': 'application/json' },
   credentials: 'include',
   body: JSON.stringify({ query: '{ refreshToken { accessToken } }' })
});

I'm just using a normal fetch

sk8Guerra avatar Jul 24 '20 22:07 sk8Guerra