Akryum / vue-cli-plugin-apollo

🚀 @vue/cli plugin for Vue Apollo

Home Page:https://vue-cli-plugin-apollo.netlify.com/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Error Network error: start received before the connection is initialised

costas90 opened this issue · comments

Version "vue-cli-plugin-apollo": "~0.21.3"

For authentication I use auth0-spa-js and hasura for the api.

Why is this happening?

I first get a warning and then the error below.
image

image

vue-apollo.js

import Vue from 'vue';
import VueApollo from 'vue-apollo';
import { createApolloClient, restartWebsockets } from 'vue-cli-plugin-apollo/graphql-client';
import { getInstance } from '@/auth/index.js';

// Install the vue plugin
Vue.use(VueApollo);

// Name of the localStorage item
const AUTH_TOKEN = 'apollo-token';

// Http endpoint
const httpEndpoint = process.env.VUE_APP_GRAPHQL_HTTP || 'https://hasura-api.herokuapp.com/v1/graphql';
// Files URL root
export const filesRoot = process.env.VUE_APP_FILES_ROOT || httpEndpoint.substr(0, httpEndpoint.indexOf('/graphql'));

Vue.prototype.$filesRoot = filesRoot;

// Config
const defaultOptions = {
  // You can use `https` for secure connection (recommended in production)
  httpEndpoint,
  // You can use `wss` for secure connection (recommended in production)
  // Use `null` to disable subscriptions
  wsEndpoint: process.env.VUE_APP_GRAPHQL_WS || 'wss://hasura-api.herokuapp.com/v1/graphql',
  // LocalStorage token
  tokenName: AUTH_TOKEN,
  // Enable Automatic Query persisting with Apollo Engine
  persisting: false,
  // Use websockets for everything (no HTTP)
  // You need to pass a `wsEndpoint` for this to work
  websocketsOnly: true,
  // Is being rendered on the server?
  ssr: false,

  // Override default apollo link
  // note: don't override httpLink here, specify httpLink options in the
  // httpLinkOptions property of defaultOptions.
  // link: myLink

  // Override default cache
  // cache: myCache

  // Override the way the Authorization header is set
  getAuth: async (tokenName) => {
    try {
      if (getInstance().isAuthenticated) {
        const token = await getInstance().getTokenSilently();
        console.log('tokeN', token);
        return token ? `Bearer ${token}` : '';
      }
    } catch (err) {
      console.log('errr', err);
    }
  }

  // Additional ApolloClient options
  // apollo: { ... }

  // Client local data (see apollo-link-state)
  // clientState: { resolvers: { ... }, defaults: { ... } }
};

// Create apollo client
export const { apolloClient, wsClient } = createApolloClient({
  ...defaultOptions
  // ...options
});

wsClient.lazy = true
wsClient.reconnect = true;
wsClient.timeout = 30000;

// Override connection params
wsClient.connectionParams = (getAuth, tokenName) => {
  const authorization = getAuth(tokenName)
  return authorization ? { headers: { authorization } } : {}
}

apolloClient.wsClient = wsClient;

// Call this in the Vue app file
export function createProvider (options = {}) {
  // Create vue apollo provider
  const apolloProvider = new VueApollo({
    defaultClient: apolloClient,
    defaultOptions: {
      $query: {
        // fetchPolicy: 'cache-and-network',
      }
    },
    errorHandler (error) {
      // eslint-disable-next-line no-console
      console.log('%cError', 'background: red; color: white; padding: 2px 4px; border-radius: 3px; font-weight: bold;', error.message);
    }
  });

  return apolloProvider;
}

// Manually call this when user log in
export async function onLogin (apolloClient, token) {
  if (typeof localStorage !== 'undefined' && token) {
    localStorage.setItem(AUTH_TOKEN, token);
  }
  if (apolloClient.wsClient) restartWebsockets(apolloClient.wsClient);
  try {
    await apolloClient.resetStore();
  } catch (e) {
    // eslint-disable-next-line no-console
    console.log('%cError on cache reset (login)', 'color: orange;', e.message);
  }
}

// Manually call this when user log out
export async function onLogout (apolloClient) {
  if (typeof localStorage !== 'undefined') {
    localStorage.removeItem(AUTH_TOKEN);
  }
  if (apolloClient.wsClient) restartWebsockets(apolloClient.wsClient);
  try {
    await apolloClient.resetStore();
  } catch (e) {
    // eslint-disable-next-line no-console
    console.log('%cError on cache reset (logout)', 'color: orange;', e.message);
  }
}

main.js

import Vue from 'vue';
import App from './App.vue';
import router from './router';
import store from './store';
import vuetify from './plugins/vuetify';
import { domain, clientId } from '@/auth_config.json';
import { Auth0Plugin } from '@/auth';
import { createProvider } from './vue-apollo';

// Install the authentication plugin here
Vue.use(Auth0Plugin, {
  domain,
  clientId,
  onRedirectCallback: appState => {
    router.push(
      appState && appState.targetUrl
        ? appState.targetUrl
        : window.location.pathname
    );
  }
});

Vue.config.productionTip = false;

new Vue({
  router,
  store,
  vuetify,
  apolloProvider: createProvider(),
  render: h => h(App)
}).$mount('#app');

I made this work with the code in the issue auth0/auth0-spa-js#401

I removed the Vue Cli Apollo plugin while trying to make this work, but I am sure if I applied the same functions in the plugin also, it could work.