Skip to content

How to set up Apollo Client 2.0, ApolloLink with subscriptions etc.. #144

Closed
@kjetilge

Description

@kjetilge

I spent some time to figure it out, so just in case anyone wants to try:

// Apollo imports
import ApolloClient from 'apollo-client';
import { HttpLink } from 'apollo-link-http';
import { ApolloLink, concat, split } from 'apollo-link';
import { InMemoryCache } from 'apollo-cache-inmemory'
import { WebSocketLink } from 'apollo-link-ws';
import { getMainDefinition } from 'apollo-utilities';

//Vue imports
import Vue from 'vue'
import VueApollo from 'vue-apollo'
import router from './router'

//Component imports
import App from './App'
import VModal from 'vue-js-modal'

import { GC_USER_ID, GC_AUTH_TOKEN } from './constants/settings'

import store from './store/index' // Vuex

const httpLink = new HttpLink({ uri: 'https://api.graph.cool/simple/v1/xxxxxxxxx' });

const authMiddleware = new ApolloLink((operation, forward) => {
  // add the authorization to the headers
  operation.setContext({
    headers: {
      authorization: localStorage.getItem(GC_AUTH_TOKEN) || null,
    }
  });
  return forward(operation);
})

// Set up subscription
const wsLink = new WebSocketLink({
  uri: `wss://subscriptions.us-west-2.graph.cool/v1/xxxxxxxx`,
  options: {
    reconnect: true
  }
});

// using the ability to split links, you can send data to each link
// depending on what kind of operation is being sent
const link = split(
  // split based on operation type
  ({ query }) => {
    const { kind, operation } = getMainDefinition(query);
    return kind === 'OperationDefinition' && operation === 'subscription';
  },
  wsLink,
  httpLink,
);

const apolloClient = new ApolloClient({
  link: concat(authMiddleware, link),
  cache: new InMemoryCache()
});

Vue.use(VueApollo)
Vue.use(VModal, { dialog: true })

Vue.config.productionTip = false

const apolloProvider = new VueApollo({
  defaultClient: apolloClient,
  defaultOptions: {
    $loadingKey: 'loading'
  },
  errorHandler (error) {
    console.log('Global error handler')
    console.error(error)
  }
})

const userId = localStorage.getItem(GC_USER_ID)
/* eslint-disable no-new */
window.vm = new Vue({
  el: '#app',
  store,
  apolloProvider,
  router,
  data: {
    userId
  },
  render: h => h(App)
})

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions