2

I'm using Angular Apollo for one of our project. I'm creating the apollo client as:

this.apollo.create({
  link: this.httpLink.create({ uri: `${environment.apiBase}/graphql?access_token=${this.tokenService.token}`}),
  cache: new InMemoryCache()
 })

Since our uri has an access token which also gets expired after a certain point of time, we had to refresh it and get the new access token, hence a new uri.

I was unable find any method in apollo docs regarding the way to update the uri(maybe I've missed it out?), also if I create a new instance like that, it throws me an error that apollo client is already present.

Is there any way to update the uri?

Manzur Khan
  • 2,366
  • 4
  • 23
  • 44

3 Answers3

1

I know it's not a part of Apollo Angular documentation (PR welcome!) but I described it in the README of apollo-angular-link-http.

There are two ways:

Use an Apollo Link to intercept the query and set uri property on the context

const authMiddleware = setContext((operation, { uri }) => {
  return refreshToken().then(res => ({
    uri: this.getURI()
  })
}))

Or intercept the request with Angular's HttpClient interceptor and change the endpoint.

Link to the package

Kamil Kisiela
  • 474
  • 4
  • 5
0

Manzur, how does the token expiration process work?

Another idea would be to send the access token via header instead of a query string. This would make it easier to send the access token. If this is possible and if you use some endpoint to refresh the token then you could use something like this:

const httpLink = new HttpLink({
  uri: `${environment.apiBase}/graphql`
})

const authMiddleware = setContext((operation, { headers }) => {
  return refreshToken().then(res => ({
    headers: {
      ...headers,
      access_token: res.access_token
    }
  })
}))

const client = new ApolloClient({
  link: from([authMiddleware, httpLink]),
  cache: new InMemoryCache()
})

ref: https://www.apollographql.com/docs/angular/recipes/authentication.html#Header

Washington Braga
  • 1,593
  • 15
  • 14
0

I was able to replace it like this:

    this.apollo.removeClient();
    this.apollo.create({
      cache: new InMemoryCache(),
      link: this.httpLink.create({
        uri: '<new-backend-url>',
      })
    });
kolypto
  • 31,774
  • 17
  • 105
  • 99