如何动态更改 Apollo Web Socket Link URI? [英] How to dynamically change Apollo Web Socket Link URI?

查看:39
本文介绍了如何动态更改 Apollo Web Socket Link URI?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前我已经像这样设置了 Apollo 的网络套接字链接:

Currently I've set up Apollo's web socket link like so:

const wsLink = new WebSocketLink({
  uri: `ws://example.com/graphql?token=${getToken()}`,
  options: {
    reconnect: true,
    connectionParams(): ConnectionParams {
      return {
        authToken: getToken(),
      };
    },
  },
});

这在连接持续时工作正常,但如果查询字符串中的令牌已过期,则需要重新建立连接时会失败.

This works fine while the connection lasts, but fails when the connection needs to be re-established if the token in the query string has expired.

我正在处理的基础设施的设置方式要求将此令牌设置为 URI 中的查询参数.如何动态更改 URI,以便在需要重新建立连接时提供新令牌?

The way the infra I'm dealing with is set up requires this token to be set as a query param in the URI. How can I dynamically change the URI so that I may provide a new token when the connection needs to be re-established?

推荐答案

您可以在函数 setContext<中手动设置属性 wsLink.subscriptionClient.url(或创建新的 subscriptionClient 实例?)/strong> https://www.apollographql.com/docs/link/links/上下文/.

You can set property wsLink.subscriptionClient.url manually (or create a new subscriptionClient instance?) in function setContext https://www.apollographql.com/docs/link/links/context/.

例如:

import { setContext } from 'apollo-link-context'
...

    const wsLink = your code...     

    const authLink = setContext(() => {
        wsLink.subscriptionClient.url = `ws://example.com/graphql?token=${getToken()}`
    })

    ...

    const config = {
        link: ApolloLink.from([
            authLink,
            wsLink
        ]),
        ...
    }

这篇关于如何动态更改 Apollo Web Socket Link URI?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆