vue.js - apollo 客户端,在不破坏使用 jwt 的 http 链接的同时添加订阅
问题描述
我目前有一个处理 HTTP 请求的 graphql api,我已经迁移到 apollo-client,现在我想添加订阅。问题是,我不知道如何组合我的 HTTP 链接(具有 JWT 身份验证中间件)。
我没有要分享的代码错误,但是,问题在于我使用链接split
方法的方式。为什么?因为当我删除它并使用authLink.concat(httpLink)
一切顺利时(除了在这种情况下我不检查连接是 WS 还是 HTTP ......)。
这是我的代码:
import Vue from "vue";
import App from "./App.vue";
import router from "./router";
// import ApolloClient from "apollo-boost"; // migrated to apollo-client
import { ApolloClient } from 'apollo-client';
import { createHttpLink } from 'apollo-link-http';
import { setContext } from 'apollo-link-context';
import { InMemoryCache } from 'apollo-cache-inmemory';
// subscriptions imports
import { split } from 'apollo-link'
import { WebSocketLink } from 'apollo-link-ws';
import { getMainDefinition } from 'apollo-utilities';
import VueApollo from "vue-apollo";
// links composition
const httpLink = createHttpLink({
uri: 'http://localhost:4000/graphql',
});
const wsLink = new WebSocketLink({
uri: `ws://localhost:5000`,
options: {
reconnect: true
}
});
// this is the sketchy section
const link = split(
({ query }) => {
const { kind, operation } = getMainDefinition(query)
return kind === 'OperationDefinition' && operation === 'subscription'
},
wsLink,
httpLink
)
// JWT middleware
const authLink = setContext((_, { headers }) => {
const token = localStorage.getItem('token');
return {
headers: {
...headers,
authorization: token ? token : ''
}
}
});
const wsPlusHttpWithJWT = authLink.concat(link)
export const apolloClient = new ApolloClient({
// link: authLink.concat(httpLink), // this worked
link: wsPlusHttpWithJWT,
cache: new InMemoryCache()
});
Vue.use(VueApollo);
const apolloProvider = new VueApollo({ defaultClient: apolloClient });
Vue.config.productionTip = false;
new Vue({
apolloProvider,
router,
render: h => h(App),
}).$mount("#app");
解决方案
推荐阅读
- python - 下面的代码通过客户端服务器网络发送一个字符串和列表
- angular - 当 ngOnInit 中的值更改时,ngIf 标志不更新 span 元素
- c++ - 为什么 C++ 允许在运行时将数组大小传递给函数以构造固定大小的数组?
- python - 为什么在退出递归调用时保留一些变量或列表,而另一些则没有?
- javascript - Bot 加入频道但不播放歌曲
- javascript - How do I replicate Gmail's "to" field where each item is an indivisible span?
- python - 如何在python中将另一个图像居中到零矩阵中?
- ios - 当用户选择要播放的新视频时关闭画中画视频
- rust - Rust - 无法运行复杂的终端命令
- linux - 从centOS7上的文本文件添加用户的脚本出现问题