This repository was archived by the owner on Feb 27, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 132
/
Copy pathapolloConfig.js
55 lines (48 loc) · 1.69 KB
/
apolloConfig.js
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
import merge from 'deepmerge'
import isEqual from 'lodash/isEqual'
// Set global state name.
export const APOLLO_STATE_PROP_NAME = '__APOLLO_STATE__'
/**
* Init Apollo and merge with initial state.
*
* @author WebDevStudios
* @see https://www.apollographql.com/docs/react/get-started/
* @param {object} apolloClient Apollo client instance.
* @param {*} initialState The initial state of things.
* @return {object} Apollo client instance.
*/
export function initializeApollo(apolloClient, initialState = null) {
// If a 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()
// Merge the existing cache into data passed from getStaticProps()/getServerSideProps().
const data = merge(initialState, existingCache, {
// Combine arrays using object equality (like in sets).
arrayMerge: (destinationArray, sourceArray) => [
...sourceArray,
...destinationArray.filter((d) =>
sourceArray.every((s) => !isEqual(d, s))
)
]
})
// Restore the cache with the merged data.
apolloClient.cache.restore(data)
}
return apolloClient
}
/**
* Pass down Apollo state to page props.
*
* @author WebDevStudios
* @param {object} client Apollo Client props.
* @param {object} pageProps Props from getStaticProps().
* @return {object} Updated page props.
*/
export function addApolloState(client, pageProps) {
if (pageProps?.props) {
pageProps.props[APOLLO_STATE_PROP_NAME] = client.cache.extract()
}
return pageProps
}