Showing
1 changed file
with
52 additions
and
6 deletions
1 | -import ApolloClient from "apollo-boost"; | 1 | +import { ApolloClient } from "apollo-client"; |
2 | +import { InMemoryCache } from "apollo-cache-inmemory"; | ||
3 | +import { HttpLink } from "apollo-link-http"; | ||
4 | +import { WebSocketLink } from "apollo-link-ws"; | ||
5 | +import { onError } from "apollo-link-error"; | ||
6 | +import { ApolloLink, split } from "apollo-link"; | ||
7 | +import { getMainDefinition } from "apollo-utilities"; | ||
8 | +import { withClientState } from "apollo-link-state"; | ||
2 | import { defaults, resolvers } from "./ClientState"; | 9 | import { defaults, resolvers } from "./ClientState"; |
10 | +import { setContext } from "apollo-link-context"; | ||
3 | 11 | ||
4 | -export default new ApolloClient({ | 12 | +const httpLink = new HttpLink({ |
5 | uri: "http://localhost:4000", | 13 | uri: "http://localhost:4000", |
6 | - clientState: { | 14 | +}); |
15 | + | ||
16 | +const wsLink = new WebSocketLink({ | ||
17 | + uri: "ws://localhost:4000", | ||
18 | + options: { | ||
19 | + reconnect: true, | ||
20 | + }, | ||
21 | +}); | ||
22 | + | ||
23 | +const setAuthorizationLink = setContext((request, previousContext) => ({ | ||
24 | + headers: { Authorization: `Bearer ${localStorage.getItem("token")}` }, | ||
25 | +})); | ||
26 | + | ||
27 | +const clientState = withClientState({ | ||
7 | defaults, | 28 | defaults, |
8 | resolvers, | 29 | resolvers, |
30 | +}); | ||
31 | + | ||
32 | +const client = new ApolloClient({ | ||
33 | + link: ApolloLink.from([ | ||
34 | + onError(({ graphQLErrors, networkError }) => { | ||
35 | + if (graphQLErrors) | ||
36 | + graphQLErrors.map(({ message, locations, path }) => | ||
37 | + console.log( | ||
38 | + `[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}` | ||
39 | + ) | ||
40 | + ); | ||
41 | + if (networkError) console.log(`[Network error]: ${networkError}`); | ||
42 | + }), | ||
43 | + setAuthorizationLink, | ||
44 | + clientState, | ||
45 | + split( | ||
46 | + ({ query }) => { | ||
47 | + const definition = getMainDefinition(query); | ||
48 | + return ( | ||
49 | + definition.kind === "OperationDefinition" && | ||
50 | + definition.operation === "subscription" | ||
51 | + ); | ||
9 | }, | 52 | }, |
10 | - headers: { | 53 | + wsLink, |
11 | - Authorization: `Bearer ${localStorage.getItem("token")}`, | 54 | + httpLink |
12 | - }, | 55 | + ), |
56 | + ]), | ||
57 | + cache: new InMemoryCache(), | ||
13 | }); | 58 | }); |
59 | +export default client; | ... | ... |
-
Please register or login to post a comment