我正在尝试设置一个处理 JWT 令牌的 apollo 客户端(每 15 分钟刷新一次),但我找不到任何像样的示例。 他们中的大多数都假设一个静态令牌并且仅使用 httpLink。
所以问题是,你如何将异步令牌添加到 httpLink 和 wsLink 的标头中 如下例所示。
...
const jwtToken = await auth.getToken()
...
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,
);