Skip to content

Instantly share code, notes, and snippets.

@good-idea
Created June 3, 2018 19:28
Show Gist options
  • Save good-idea/a9e7a8538146b368e7789a5f2c9df13b to your computer and use it in GitHub Desktop.
Save good-idea/a9e7a8538146b368e7789a5f2c9df13b to your computer and use it in GitHub Desktop.
Apollo error logging problems
// @flow
import React from 'react'
import type { Node } from 'react'
import { ApolloProvider } from 'react-apollo'
import { ApolloLink } from 'apollo-link'
import { ApolloClient } from 'apollo-client'
import { onError } from 'apollo-link-error'
import { InMemoryCache } from 'apollo-cache-inmemory'
import { createUploadLink } from 'apollo-upload-client'
import { getCookie } from 'Utils/storage'
import { VIEWER_COOKIE_TOKEN } from 'Constants'
const uploadLink = createUploadLink({ uri: '/api', credentials: 'same-origin' })
// TODO Return IDs from more objects for better caching
const cache = new InMemoryCache({
addTypename: true,
dataIdFromObject: (object) => {
switch (object.__typename) {
case 'image':
return object.publicId
default:
return object.uid || null
}
},
})
const setAuthHeader = new ApolloLink((operation, forward) => {
const authCookie = getCookie(VIEWER_COOKIE_TOKEN)
if (authCookie) {
operation.setContext({
headers: { Authorization: authCookie },
})
}
return forward(operation)
})
const logQueries = new ApolloLink((operation, forward) => {
const labelStyle = 'color: deepskyblue; font-weight: 800'
const messageStyle = 'color: gray'
if (process.env.NODE_ENV === 'development') {
console.log(`%c[GraphQL Logger] %c(link) Called ${operation.operationName}`, labelStyle, messageStyle)
if (operation.variables) console.log(' variables ⤑ ', operation.variables)
}
return forward(operation).map((result) => {
if (process.env.NODE_ENV === 'development') {
console.log(`%c[GraphQL Logger]%c (link) received result from ${operation.operationName}:`, labelStyle, messageStyle)
console.log(' ⤑ ', result.data)
}
return result
})
})
const logErrors = onError((err) => {
console.log(err)
const { graphQLErrors, networkError } = err
console.log(networkError.result)
console.log(networkError.response.text())
if (graphQLErrors) {
graphQLErrors.map(({ message, locations, path }) => {
console.log(`[GraphQL Error] Message: ${message}, Location: ${locations}, Path: ${path}`)
console.log(' ⤑ ', message)
console.log(' ⤑ ', locations)
return false
})
}
if (networkError) console.log(`[Network Error] ${networkError}`, networkError.response, networkError.response.body)
})
const link = ApolloLink.from([setAuthHeader, logErrors, logQueries, uploadLink])
const client = new ApolloClient({ link, cache })
const ApolloWrapper = (props: { children: Node }) => <ApolloProvider client={client}>{props.children}</ApolloProvider>
export default ApolloWrapper
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment