@@ -22,16 +22,20 @@ type ContextWithApolloOptions = AppContext & {
22
22
} & NextPageContext &
23
23
WithApolloOptions ;
24
24
25
+ type ApolloClientParam = ApolloClient < NormalizedCacheObject >
26
+ | ( ( ctx ?: NextPageContext ) => ApolloClient < NormalizedCacheObject > )
27
+
25
28
/**
26
29
* Installs the Apollo Client on NextPageContext
27
30
* or NextAppContext. Useful if you want to use apolloClient
28
31
* inside getStaticProps, getStaticPaths or getServerSideProps
29
32
* @param {NextPageContext | AppContext } ctx
30
33
*/
31
34
export const initOnContext = (
32
- ac : ApolloClient < NormalizedCacheObject > ,
35
+ acp : ApolloClientParam ,
33
36
ctx : ContextWithApolloOptions
34
37
) => {
38
+ const ac = typeof acp === 'function' ? acp ( ctx ) : acp as ApolloClient < NormalizedCacheObject > ;
35
39
const inAppContext = Boolean ( ctx . ctx ) ;
36
40
37
41
// We consider installing `withApollo({ ssr: true })` on global App level
@@ -76,10 +80,12 @@ export const initOnContext = (
76
80
* @param {NextPageContext } ctx
77
81
*/
78
82
const initApolloClient = (
79
- apolloClient : ApolloClient < NormalizedCacheObject > ,
83
+ acp : ApolloClientParam ,
80
84
initialState : NormalizedCacheObject ,
81
85
ctx : NextPageContext | undefined
82
86
) => {
87
+ const apolloClient = typeof acp === 'function' ? acp ( ctx ) : acp as ApolloClient < NormalizedCacheObject > ;
88
+
83
89
// Make sure to create a new client for every server-side request so that data
84
90
// isn't shared between connections (which would be bad)
85
91
if ( typeof window === "undefined" ) {
@@ -98,11 +104,11 @@ const initApolloClient = (
98
104
* Creates a withApollo HOC
99
105
* that provides the apolloContext
100
106
* to a next.js Page or AppTree.
101
- * @param {Object } withApolloOptions
107
+ * @param {Object } ac
102
108
* @param {Boolean } [withApolloOptions.ssr=false]
103
109
* @returns {(PageComponent: NextPage) => ComponentClass<P> | FunctionComponent<P> }
104
110
*/
105
- export default ( ac : ApolloClient < NormalizedCacheObject > ) => {
111
+ export default ( ac : ApolloClientParam ) => {
106
112
return ( { ssr = false } = { } ) => ( PageComponent : NextPage ) => {
107
113
const WithApollo = ( {
108
114
apolloClient,
@@ -211,10 +217,11 @@ export default (ac: ApolloClient<NormalizedCacheObject>) => {
211
217
} ;
212
218
213
219
const createApolloClient = (
214
- apolloClient : ApolloClient < NormalizedCacheObject > ,
220
+ acp : ApolloClientParam ,
215
221
initialState : NormalizedCacheObject ,
216
222
ctx : NextPageContext | undefined
217
- ) => {
223
+ ) => {
224
+ const apolloClient = typeof acp === 'function' ? acp ( ctx ) : acp as ApolloClient < NormalizedCacheObject > ;
218
225
// The `ctx` (NextPageContext) will only be present on the server.
219
226
// use it to extract auth headers (ctx.req) or similar.
220
227
( apolloClient as ApolloClient < NormalizedCacheObject > & {
0 commit comments