Skip to content

Instantly share code, notes, and snippets.

@zamson
Created June 17, 2020 05:16
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 zamson/f4aa0b6d5ce5e93a38e7fb9bee6857fa to your computer and use it in GitHub Desktop.
Save zamson/f4aa0b6d5ce5e93a38e7fb9bee6857fa to your computer and use it in GitHub Desktop.
import {
ApolloClient,
ApolloLink,
from,
HttpLink,
InMemoryCache,
} from '@apollo/client'
import { onError } from 'apollo-link-error'
import fetch from 'isomorphic-fetch'
import possibleTypes from './possibleTypes.json'
const httpLink = new HttpLink({
uri: process.env.GATSBY_GRAPHQL_URL,
fetch,
credentials: 'include',
})
const middleware = new ApolloLink((operation, forward) => {
const session = process.browser && localStorage.getItem('woo-session')
if (session) {
operation.setContext(() => ({
headers: {
'woocommerce-session': `Session ${session}`,
},
}))
}
return forward(operation)
})
const onErrorLink = onError(({ graphQLErrors, networkError }) => {
if (graphQLErrors) {
graphQLErrors.forEach(({ message, locations, path, extensions }) => {
console.log(`[GraphQL error]:`, {
Message: message,
Location: locations,
Path: path,
Extension: extensions,
})
})
}
if (networkError) {
console.log(`[Network error]: ${networkError}`)
}
})
/**
* Afterware operation.
*
* This catches the incoming session token and stores it in localStorage, for future GraphQL requests.
*/
export const afterware = new ApolloLink((operation, forward) =>
forward(operation).map(response => {
/**
* Check for session header and update session in local storage accordingly.
*/
const context = operation.getContext()
const {
response: { headers },
} = context
console.log('Headers: ')
console.log(headers.get('woocommerce-session'))
const session = headers.get('woocommerce-session')
if (session) {
// Remove session data if session destroyed.
if (session === 'false') {
localStorage.removeItem('woo-session')
// Update session new data if changed.
} else if (localStorage.getItem('woo-session') !== session) {
localStorage.setItem('woo-session', headers.get('woocommerce-session'))
}
}
return response
})
)
export const client = new ApolloClient({
link: from([middleware, onErrorLink, afterware, httpLink]),
cache: new InMemoryCache({ possibleTypes }),
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment