Updating uri of apollo client instance

China☆狼群 提交于 2020-06-17 00:14:11

问题


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?


回答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




回答2:


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



来源:https://stackoverflow.com/questions/51112677/updating-uri-of-apollo-client-instance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!