|
| 1 | +import { createApolloClient } from 'vue-cli-plugin-apollo/graphql-client'; |
| 2 | +import Vue from 'vue'; |
| 3 | +import VueApollo from 'vue-apollo'; |
| 4 | + |
| 5 | +Vue.use(VueApollo); |
| 6 | + |
| 7 | +const AUTH_TOKEN = `apollo-token`; |
| 8 | + |
| 9 | +const httpEndpoint = process.env.VUE_APP_GRAPHQL_HTTP || `/.netlify/functions/graphql`; |
| 10 | +const defaultOptions = { |
| 11 | + httpEndpoint, |
| 12 | + tokenName: AUTH_TOKEN, |
| 13 | + persisting: false, |
| 14 | + websocketsOnly: false, |
| 15 | + ssr: false, |
| 16 | +}; |
| 17 | + |
| 18 | +export function createProvider(options = {}) { |
| 19 | + const { apolloClient } = createApolloClient({ |
| 20 | + ...defaultOptions, |
| 21 | + ...options, |
| 22 | + }); |
| 23 | + |
| 24 | + const apolloProvider = new VueApollo({ |
| 25 | + defaultClient: apolloClient, |
| 26 | + defaultOptions: { |
| 27 | + $query: {}, |
| 28 | + }, |
| 29 | + errorHandler(error) { |
| 30 | + // eslint-disable-next-line no-console |
| 31 | + console.log(`%cError`, `background: red; color: white; padding: 2px 4px; border-radius: 3px; font-weight: bold;`, error.message); |
| 32 | + }, |
| 33 | + }); |
| 34 | + |
| 35 | + return apolloProvider; |
| 36 | +} |
| 37 | + |
| 38 | +export async function onLogin(apolloClient, token) { |
| 39 | + if (typeof localStorage !== `undefined` && token) { |
| 40 | + localStorage.setItem(AUTH_TOKEN, token); |
| 41 | + } |
| 42 | + try { |
| 43 | + await apolloClient.resetStore(); |
| 44 | + } catch (e) { |
| 45 | + // eslint-disable-next-line no-console |
| 46 | + console.log(`%cError on cache reset (login)`, `color: orange;`, e.message); |
| 47 | + } |
| 48 | +} |
| 49 | + |
| 50 | +export async function onLogout(apolloClient) { |
| 51 | + if (typeof localStorage !== `undefined`) { |
| 52 | + localStorage.removeItem(AUTH_TOKEN); |
| 53 | + } |
| 54 | + try { |
| 55 | + await apolloClient.resetStore(); |
| 56 | + } catch (e) { |
| 57 | + // eslint-disable-next-line no-console |
| 58 | + console.log(`%cError on cache reset (logout)`, `color: orange;`, e.message); |
| 59 | + } |
| 60 | +} |
0 commit comments