Apollo Client fix for authentication

This commit is contained in:
mati108@gmail.com committed 2018-10-15 09:43:56 -03:00
1 parent 2d198bacb8
commit 8914586a45
2 files changed
+8 -52

No files matched your search

+7 -50
View File
@@ -4,9 +4,6 @@ import { InMemoryCache } from 'apollo-cache-inmemory'
import { ApolloLink, Observable } from 'apollo-link'
import { onError } from 'apollo-link-error'
import { setContext } from 'apollo-link-context'
// import { WebSocketLink } from 'apollo-link-ws'
// import { SubscriptionClient } from 'subscriptions-transport-ws'
// import { getMainDefinition } from 'apollo-utilities'
import { getItem } from '../utils/local-storage'
@@ -15,47 +12,8 @@ const graphqlEndpoint =
? process.env.PROD_GRAPHQL
: process.env.DEV_GRAPHQL
/*
const wsUri = graphqlEndpoint.replace(/^http/, 'ws')
const globalVar =
typeof global !== 'undefined'
? global
: typeof window !== 'undefined'
? window
: {}
const webSocketImpl = globalVar.WebSocket || globalVar.MozWebSocket
const wsClient = new SubscriptionClient(
wsUri,
{
reconnect: true
},
webSocketImpl
)
wsClient.onDisconnected(() => {
// console.log('onDisconnected')
})
wsClient.onReconnected(() => {
// console.log('onReconnected')
})
*/
const httpLink = new HttpLink({ uri: graphqlEndpoint })
/*
const link = split(
({ query }) => {
const { kind, operation } = getMainDefinition(query)
return kind === 'OperationDefinition' && operation === 'subscription'
},
// new WebSocketLink(wsClient),
httpLink
)
*/
const authRetryLink = onError(
({ graphQLErrors, networkError, operation, forward }) => {
if (graphQLErrors) {
@@ -96,16 +54,15 @@ const authRetryLink = onError(
}
)
const authLink = setContext(async (_, { headers }) => {
const authLink = setContext((_, { headers }) => {
// get the authentication token from local storage if it exists
await getItem('access_token').then(token => {
return {
headers: {
...headers,
Authorization: token ? `Bearer ${token}` : ``
}
const token = localStorage.getItem('access_token')
return {
headers: {
...headers,
Authorization: token ? `Bearer ${token}` : ``
}
})
}
})
const cache = new InMemoryCache().restore(window.__APOLLO_STATE__)
+1 -2
View File
@@ -22,11 +22,10 @@ export const createRemoteSchema = async (uri) => {
const http = makeDatabaseServiceLink()
const authLink = setContext((request, previousContext) => {
console.log(previousContext.graphqlContext.headers)
return (
{
headers: {
Authorization: previousContext.graphqlContext.headers.Authorization ? previousContext.graphqlContext.headers.Authorization : ''
Authorization: previousContext.graphqlContext.headers.authorization ? previousContext.graphqlContext.headers.authorization : ''
}
}
)