withApollo.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. /**
  2. * Using next-with-apollo
  3. * https://github.com/lfades/next-with-apollo
  4. *
  5. * Changes:
  6. * * Reading endpoint and prodEndpoint from a config file
  7. * * Setting request to handle credentials.
  8. */
  9. import withApollo from 'next-with-apollo'
  10. import ApolloClient from 'apollo-client'
  11. import { InMemoryCache } from 'apollo-cache-inmemory'
  12. import { onError } from 'apollo-link-error'
  13. import { ApolloLink } from 'apollo-link'
  14. import { createUploadLink } from 'apollo-upload-client'
  15. import { endpoint, prodEndpoint } from '../config'
  16. import { resolvers, typeDefs, initialState } from './localState'
  17. const cache = new InMemoryCache()
  18. function createClient ({ ctx, headers }) {
  19. return new ApolloClient({
  20. link: ApolloLink.from([
  21. onError(({ graphQLErrors, networkError }) => {
  22. if (graphQLErrors) {
  23. graphQLErrors.map(({ message, locations, path }) =>
  24. console.log(
  25. `[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`
  26. )
  27. )
  28. }
  29. if (networkError) console.log(`[Network error]: ${networkError}`)
  30. }),
  31. createUploadLink({
  32. uri: process.env.NODE_ENV === 'development' ? endpoint : prodEndpoint,
  33. headers,
  34. credentials: 'include'
  35. })
  36. ]),
  37. fetchOptions: { mode: 'no-cors' },
  38. cache,
  39. resolvers,
  40. typeDefs
  41. })
  42. }
  43. cache.writeData(initialState)
  44. export default withApollo(createClient)