Skip to content

Instantly share code, notes, and snippets.

@oller
Created April 11, 2019 08:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save oller/3be0105bb6a0f723919cef05c416fb05 to your computer and use it in GitHub Desktop.
Save oller/3be0105bb6a0f723919cef05c416fb05 to your computer and use it in GitHub Desktop.
vue apollo config middleware link working for dynamic additional headers
import Vue from 'vue'
import VueApollo from 'vue-apollo'
import {
createApolloClient,
restartWebsockets
} from 'vue-cli-plugin-apollo/graphql-client'
import { setContext } from 'apollo-link-context'
import authConfig from '@/../auth_config.json'
const middlewareLink = setContext((_, { headers }) => {
// Logic to retrieve additional headers
let impersonate
let impersonateHeader
if (localStorage.getItem('impersonate')) {
try {
impersonate = JSON.parse(localStorage.getItem('impersonate'))
} catch (e) {
localStorage.removeItem('impersonate')
}
}
if (impersonate && impersonate.length) {
impersonateHeader = {
'impersonate': impersonate[impersonate.length - 1]
}
}
// Apply headers along with existing headers
return {
headers: {
...headers,
...impersonateHeader
}
}
})
// Install the vue plugin
Vue.use(VueApollo)
// Name of the localStorage item
const AUTH_TOKEN = authConfig.localTokenName
// Http endpoint
const httpEndpoint =
process.env.VUE_APP_GRAPHQL_HTTP || 'http://localhost:18080/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 || 'ws://localhost:18080/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: false,
// 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: middlewareLink,
// Override default cache
// cache: myCache
// Override the way the Authorization header is set
getAuth: () => {
// get the authentication token from local storage if it exists
const token = localStorage.getItem(AUTH_TOKEN)
// return the headers to the context so httpLink can read them
if (token) {
return 'Bearer ' + token
} else {
return ''
}
}
// Additional ApolloClient options
// apollo: { ... }
// Client local data (see apollo-link-state)
// clientState: { resolvers: { ... }, defaults: { ... } }
}
// Call this in the Vue app file
export function createProvider(options = {}) {
// Create apollo client
const { apolloClient, wsClient } = createApolloClient({
...defaultOptions,
...options
})
apolloClient.wsClient = wsClient
// 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) {
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 (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)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment