首页 > 解决方案 > 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");

标签: vue.jsgraphqlapollo-clientgraphql-subscriptionsvue-apollo

解决方案


推荐阅读