Created
June 22, 2020 05:47
-
-
Save zamson/6b0ee34d279c3791004655e2a6295739 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { | |
ApolloClient, | |
ApolloLink, | |
HttpLink, | |
InMemoryCache, | |
defaultDataIdFromObject, | |
} from '@apollo/client' | |
import { onError } from 'apollo-link-error' | |
import fetch from 'isomorphic-fetch' | |
import { get, isEmpty } from 'lodash' | |
// import possibleTypes from './possibleTypes.json' | |
// Local imports | |
import { typeDefs, resolvers } from './schema' | |
// Apollo Caching configuration | |
const cache = new InMemoryCache({ | |
dataIdFromObject: object => { | |
// eslint-disable-next-line | |
switch (object.__typename) { | |
case 'CartItem': | |
return object.key | |
default: | |
return object.id || defaultDataIdFromObject(object) | |
} | |
}, | |
}) | |
// Authorization middleware | |
const middleware = new ApolloLink((operation, forward) => { | |
/** | |
* If session data exist in local storage, set value as session header. | |
*/ | |
const session = process.browser ? localStorage.getItem('woo-session') : null | |
if (session) { | |
operation.setContext(({ headers = {} }) => ({ | |
headers: { | |
'woocommerce-session': `Session ${session}`, | |
}, | |
})) | |
} | |
return forward(operation) | |
}) | |
// Authorization afterware | |
const afterware = new ApolloLink((operation, forward) => | |
forward(operation).map(response => { | |
// Update session data. | |
const context = operation.getContext() | |
const { | |
response: { headers }, | |
} = context | |
const session = headers.get('woocommerce-session') | |
if (session) { | |
if (session === 'false') { | |
localStorage.removeItem('woo-session') | |
} else if (localStorage.getItem('woo-session') !== session) { | |
localStorage.setItem('woo-session', headers.get('woocommerce-session')) | |
} | |
} | |
// Update token if changed. | |
const authToken = get(response, 'data.login.authToken') | |
if (authToken && authToken !== localStorage.getItem('user-token')) { | |
localStorage.setItem('user-token', authToken) | |
} | |
return response | |
}) | |
) | |
const onForbidden = onError(({ networkError }) => { | |
if (networkError && networkError.statusCode === 403) { | |
localStorage.clear() | |
} | |
}) | |
const httpLink = new HttpLink({ | |
uri: process.env.GATSBY_GRAPHQL_URL, | |
fetch, | |
credentials: 'include', | |
}) | |
export const client = new ApolloClient({ | |
link: onForbidden.concat(middleware.concat(afterware.concat(httpLink))), | |
cache, | |
clientState: {}, | |
typeDefs, | |
resolvers, | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment