-
Notifications
You must be signed in to change notification settings - Fork 1
/
apollo.tsx
228 lines (197 loc) · 7.6 KB
/
apollo.tsx
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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
import React from 'react';
import Head from 'next/head';
import fetch from 'isomorphic-unfetch';
import { ApolloProvider } from '@apollo/react-hooks';
import { ApolloClient } from 'apollo-client';
import { InMemoryCache } from 'apollo-cache-inmemory';
import { ApolloLink, split } from 'apollo-link';
import { BatchHttpLink } from 'apollo-link-batch-http';
import { onError } from 'apollo-link-error';
import { HttpLink } from 'apollo-link-http';
import { toIdValue } from 'apollo-utilities';
import { fragmentMatcher } from './fragment-matcher';
import { version, name } from '../package.json';
const isBrowser = typeof window !== 'undefined';
const uri = isBrowser
? `${window.location.origin}/api/graphql`
: process.env.GRAPHQL_ENDPOINT
? process.env.GRAPHQL_ENDPOINT
: 'http://localhost:3000/api/graphql';
const cache: any = new InMemoryCache({
cacheRedirects: {
Query: {
// Here we map the data we get in product list view with the one for detail view
// see: https://www.apollographql.com/docs/react/features/performance.html
getProduct: (_, args) =>
toIdValue(
cache.config.dataIdFromObject({
__typename: 'Product',
id: args.id,
}),
),
},
},
resultCaching: false,
});
const batchHttpLink = new BatchHttpLink({
uri,
credentials: 'include', // 'same-origin'
headers: { batch: 'true ' },
batchInterval: 10,
...(!isBrowser && { fetch }),
});
// link to use if not batching
const httpLink = new HttpLink({
uri,
credentials: 'include', // 'same-origin'
...(!isBrowser && { fetch }),
});
let apolloClient: any = null;
export function withApollo(PageComponent: any, { ssr = true } = {}) {
const WithApollo = ({
apolloClient,
apolloState,
ssrComplete,
...pageProps
}: any) => {
const client = apolloClient || initApolloClient(apolloState);
return typeof window !== 'undefined' || (ssr && !ssrComplete) ? (
<ApolloProvider client={client}>
<PageComponent {...pageProps} />
</ApolloProvider>
) : null;
};
// Set the correct displayName in development
if (process.env.NODE_ENV !== 'production') {
const displayName =
PageComponent.displayName || PageComponent.name || 'Component';
if (displayName === 'App') {
console.warn('This withApollo HOC only works with PageComponents.');
}
WithApollo.displayName = `withApollo(${displayName})`;
}
if (ssr || PageComponent.getInitialProps) {
WithApollo.getInitialProps = async (ctx: any) => {
const { AppTree } = ctx;
// Initialize ApolloClient, add it to the ctx object so
// we can use it in `PageComponent.getInitialProp`.
ctx.apolloClient = initApolloClient();
// Run wrapped getInitialProps methods
let pageProps = {};
if (PageComponent.getInitialProps) {
pageProps = await PageComponent.getInitialProps(ctx);
}
// Only on the server:
if (typeof window === 'undefined') {
// When redirecting, the response is finished.
// No point in continuing to render
if (ctx.res && ctx.res.finished) {
return pageProps;
}
// Only if ssr is enabled
if (ssr) {
try {
// Run all GraphQL queries
const { getDataFromTree } = await import(
'@apollo/react-ssr'
);
await getDataFromTree(
<AppTree
pageProps={{
...pageProps,
apolloClient: ctx.apolloClient,
}}
/>,
);
} catch (error) {
// This error will not happen with config in line 205 below!!!
console.error(
`[GraphQL treewalker error] Error ${error.message}`,
);
}
// getDataFromTree does not call componentWillUnmount
// head side effect therefore need to be cleared manually
Head.rewind();
}
}
// Extract query data from the Apollo store
const apolloState = ctx.apolloClient.cache.extract();
return {
...pageProps,
apolloState,
ssrComplete: true,
};
};
}
return WithApollo;
}
function initApolloClient(initialState = undefined) {
// Make sure to create a new client for every server-side request so that data
// isn't shared between connections (which would be bad)
if (typeof window === 'undefined') {
return createApolloClient(initialState);
}
// Reuse client on the client-side
if (!apolloClient) {
apolloClient = createApolloClient(initialState);
}
return apolloClient;
}
function createApolloClient(initialState = {}) {
const isClientSide = typeof window !== 'undefined';
// Create the cache first, which we'll share across Apollo tooling.
// This is an in-memory cache. Since we'll be calling `createClient` on
// universally, the cache will survive until the HTTP request is
// responded to (on the server) or for the whole of the user's visit (in
// the browser)
const cache = new InMemoryCache({
fragmentMatcher,
// addTypename: false FIXME: find out how to get cache working while not retrieving all __typename
cacheRedirects: {
Query: {
// Here we can map the data we get in list view with the one for detail view
// see: https://www.apollographql.com/docs/react/performance/performance/
},
},
});
// If we're in the browser, we'd have received initial state from the
// server. Restore it, so the client app can continue with the same data.
let currentCache;
if (isClientSide) {
currentCache = cache.restore((window as any).__APOLLO_STATE__);
}
return new ApolloClient({
name,
version,
ssrMode: typeof window === 'undefined', // Disables forceFetch on the server (so queries are only run once)
link: ApolloLink.from([
onError(({ graphQLErrors, networkError }) => {
if (graphQLErrors)
graphQLErrors.map(({ message, locations, path }) =>
console.log(
`[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`,
),
);
if (networkError)
console.log(`[Network error]: ${networkError}`);
}),
split(
(operation) => operation.getContext().important === true,
httpLink as any, // if the test is true -- debatch
batchHttpLink as any, // otherwise, batching is fine
),
]),
cache: currentCache || cache,
defaultOptions: {
query: {
errorPolicy: 'all',
},
mutate: {
errorPolicy: 'all',
},
watchQuery: {
errorPolicy: 'all',
},
},
});
}