【问题标题】:Updating uri of apollo client instance更新 apollo 客户端实例的 uri
【发布时间】:2018-12-09 07:04:21
【问题描述】:

我在我们的一个项目中使用 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 吗?

【问题讨论】:

    标签: javascript angular graphql apollo


    【解决方案1】:

    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

    【讨论】:

      【解决方案2】:

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

      有两种方式:

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

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

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

      Link to the package

      【讨论】:

        【解决方案3】:

        我可以这样替换它:

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

        【讨论】:

          猜你喜欢
          • 2020-01-04
          • 2021-10-22
          • 2021-03-11
          • 2018-11-04
          • 2021-10-01
          • 2021-07-30
          • 2019-04-02
          • 2018-08-17
          • 1970-01-01
          相关资源
          最近更新 更多