使用 httpLink 和 wsLink 向 apollo 客户端添加动态 jwt 令牌

时间:2021-01-16 16:56:37

标签: asynchronous jwt apollo-client

我正在尝试设置一个处理 JWT 令牌的 apollo 客户端(每 15 分钟刷新一次),但我找不到任何像样的示例。 他们中的大多数都假设一个静态令牌并且仅使用 httpLink。

所以问题是,你如何将异步令牌添加到 httpLink 和 wsLink 的标头中 如下例所示。

  1. 异步获取令牌
    ...
    const jwtToken = await auth.getToken()
    ...

  1. 将令牌添加到 httpLink 和 wsLink 的标头
    import { split, HttpLink } from '@apollo/client';
    import { getMainDefinition } from '@apollo/client/utilities';
    import { WebSocketLink } from '@apollo/client/link/ws';
    
    const httpLink = new HttpLink({
      uri: 'http://localhost:3000/'
    });
    
    const wsLink = new WebSocketLink({
      uri: `ws://localhost:5000/`,
      options: {
        reconnect: true
      }
    });
    
    // The split function takes three parameters:
    //
    // * A function that's called for each operation to execute
    // * The Link to use for an operation if the function returns a "truthy" value
    // * The Link to use for an operation if the function returns a "falsy" value
    const splitLink = split(
      ({ query }) => {
        const definition = getMainDefinition(query);
        return (
          definition.kind === 'OperationDefinition' &&
          definition.operation === 'subscription'
        );
      },
      wsLink,
      httpLink,
    );

0 个答案:

没有答案