正在更新apollo客户端实例的uri



我正在为我们的一个项目使用Angular Apollo。我正在创建apollo客户端为:

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

由于我们的uri有一个访问令牌,在某个时间点后也会过期,因此我们必须刷新它并获取新的访问令牌,从而获得一个新的uri。

我在apollo文档中找不到任何关于更新uri的方法(也许我错过了?),而且如果我创建这样的新实例,它会给我一个错误,即apollo客户端已经存在。

有什么方法可以更新uri吗?

我知道它不是Apollo Angular文档的一部分(欢迎PR!),但我在apollo-angular-link-http的自述文件中对此进行了描述。

有两种方式:

使用Apollo链接拦截查询并在上下文上设置uri属性

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

或者使用Angular的HttpClient拦截器拦截请求并更改端点。

到包的链接

Manzur,令牌到期过程是如何工作的?

另一个想法是通过标头而不是查询字符串发送访问令牌。这将使发送访问令牌更加容易。如果这是可能的,如果你使用某个端点来刷新令牌,那么你可以使用这样的东西:

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()
})

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

我可以这样替换它:

this.apollo.removeClient();
this.apollo.create({
cache: new InMemoryCache(),
link: this.httpLink.create({
uri: '<new-backend-url>',
})
});

最新更新