Created
May 2, 2020 17:29
-
-
Save vacom/3478901406df2e41e590bbbb6b70efec to your computer and use it in GitHub Desktop.
Apollo config
This file contains hidden or 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 } from "apollo-client"; | |
import { createHttpLink } from "apollo-link-http"; | |
import { setContext } from "apollo-link-context"; | |
import { InMemoryCache } from "apollo-cache-inmemory"; | |
import { WebSocketLink } from "apollo-link-ws"; | |
import { split } from "apollo-link"; | |
import { getMainDefinition } from "apollo-utilities"; | |
function createApolloClient(idToken: string | undefined) { | |
const cache = new InMemoryCache(); | |
const httpLink = createHttpLink({ | |
uri: process.env.REACT_APP_API_URL | |
}); | |
const wsLink = new WebSocketLink({ | |
uri: process.env.REACT_APP_API_SUBSCRIPTION_URL, | |
options: { | |
reconnect: true, | |
connectionParams: { | |
Authorization: `Bearer ${idToken}` | |
} | |
} | |
}); | |
const authLink = setContext((_, { headers }) => { | |
return { | |
headers: { | |
...headers, | |
Authorization: `Bearer ${idToken}` | |
} | |
}; | |
}); | |
const link = split( | |
// split based on operation type | |
({ query }) => { | |
let definition = getMainDefinition(query); | |
return ( | |
definition.kind === "OperationDefinition" && | |
definition.operation === "subscription" | |
); | |
}, | |
wsLink, | |
authLink.concat(httpLink) | |
); | |
return new ApolloClient({ | |
link, | |
cache | |
}); | |
} | |
export default createApolloClient; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment