forked from forbole/big-dipper-2.0-cosmos
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.ts
101 lines (86 loc) · 2.38 KB
/
client.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
import WebSocket from 'isomorphic-ws';
import {
ApolloClient,
InMemoryCache,
split,
HttpLink,
ApolloLink,
concat,
} from '@apollo/client';
import {
getMainDefinition,
} from '@apollo/client/utilities';
import { WebSocketLink } from '@apollo/client/link/ws';
import { useMemo } from 'react';
const defaultOptions:any = {
watchQuery: {
fetchPolicy: 'no-cache',
errorPolicy: 'all',
},
query: {
fetchPolicy: 'no-cache',
errorPolicy: 'all',
},
};
let apolloClient;
const httpLink = new HttpLink({
uri: process.env.NEXT_PUBLIC_GRAPHQL_URL,
});
const wsLink = new WebSocketLink({
uri: process.env.NEXT_PUBLIC_GRAPHQL_WS ?? 'wss://localhost:3000',
options: {
reconnect: true,
},
webSocketImpl: WebSocket,
});
const link = typeof window !== 'undefined' ? split(
({ query }) => {
const {
kind, operation,
}:any = getMainDefinition(query);
return kind === 'OperationDefinition' && operation === 'subscription';
},
wsLink,
httpLink,
) : httpLink;
const authMiddleware = new ApolloLink((operation, forward) => {
operation.setContext({
headers: {
},
});
return forward(operation);
});
function createApolloClient() {
const client = new ApolloClient({
ssrMode: typeof window === 'undefined',
link: concat(authMiddleware, link),
cache: new InMemoryCache({
}),
});
client.defaultOptions = defaultOptions;
return client;
}
export function initializeApollo(initialState = null) {
// eslint-disable-next-line
const _apolloClient = apolloClient ?? createApolloClient();
// If your page has Next.js data fetching methods that use Apollo Client, the initial state
// gets hydrated here
if (initialState) {
// Get existing cache, loaded during client side data fetching
const existingCache = _apolloClient.extract();
// Restore the cache using the data passed from getStaticProps/getServerSideProps
// combined with the existing cached data
_apolloClient.cache.restore({
...existingCache, ...initialState,
});
}
// For SSG and SSR always create a new Apollo Client
if (typeof window === 'undefined') return _apolloClient;
// Create the Apollo Client once in the client
if (!apolloClient) apolloClient = _apolloClient;
return _apolloClient;
}
export function useApollo(initialState) {
const store = useMemo(() => initializeApollo(initialState), [initialState]);
return store;
}