Skip to content

Instantly share code, notes, and snippets.

@KATT
Created March 17, 2017 19:11
Show Gist options
  • Save KATT/06e4bf7cd09ba17e2ae2c656847bba3f to your computer and use it in GitHub Desktop.
Save KATT/06e4bf7cd09ba17e2ae2c656847bba3f to your computer and use it in GitHub Desktop.
import { ApolloClient, createNetworkInterface } from 'react-apollo';
let apolloClient = null;
function createClient(headers, userToken) {
const networkInterface = createNetworkInterface({
uri: 'https://api.graph.cool/simple/v1/Groopy',
opts: {
credentials: 'same-origin',
// Pass headers here if your graphql server requires them
},
});
networkInterface.use([{
applyMiddleware(req, next) {
if (!req.options.headers) {
req.options.headers = {}; // eslint-disable-line no-param-reassign
}
if (userToken) {
req.options.headers.authorization = `Bearer ${userToken}`; // eslint-disable-line no-param-reassign
} else if (req.options.headers.authorization) {
delete req.options.headers.authorization; // eslint-disable-line no-param-reassign
}
next();
},
}]);
return new ApolloClient({
ssrMode: !process.browser,
dataIdFromObject: result => result.id || null,
networkInterface,
});
}
export const initClient = (headers) => {
if (!process.browser) {
return createClient(headers);
}
if (!apolloClient) {
apolloClient = createClient(headers);
}
return apolloClient;
};
export default initClient;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment