This repository has been archived by the owner on Aug 22, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
nextApollo.js
90 lines (80 loc) · 2.46 KB
/
nextApollo.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
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
/* @flow */
const { createElement, PureComponent } = require('react')
const Head = require('next/head').default
const { getDataFromTree } = require('react-apollo')
const { isNode } = require('./constants')
const noop = require('lodash/noop')
/*::
import ApolloClient from 'apollo-client'
import App from 'next/app'
*/
/**
* Apollo-Client HOC for the Next.js
* {@link https://nextjs.org/docs/#custom-app|App} component.
*
* A simpler way to achieve the same result as in
* {@link https://github.com/zeit/next.js/tree/master/examples/with-apollo|with-apollo},
* which does not require any boilerplate code.
*
* The `ctx` object is equivalent to the one received in all
* {@link https://nextjs.org/docs/#fetching-data-and-component-lifecycle|getInitialProps}
* hooks.
*
* @example
* import React from 'react'
* import App, { Container } from 'next/app'
* import { ApolloProvider } from 'react-apollo'
* import nextApollo from 'secondwheel/nextApollo'
* import ApolloClient from 'secondwheel/ApolloClient'
*
* class MyApp extends App {
* render () {
* const { Component, pageProps, client } = this.props
*
* return (
* <Container>
* <ApolloProvider client={client}>
* <Component {...pageProps} />
* </ApolloProvider>
* </Container>
* )
* }
* }
*
* export default nextApollo(
* props => new ApolloClient({ uri: 'http://localhost:4000', ...props })
* )(MyApp)
*/
const nextApollo = (
getClient/*: (props: Object, ctx?: Object) => ApolloClient */,
getProps/*: (ctx: Object) => ?Object | Promise<?Object> */ = noop
) => (app/*: App */) => class extends PureComponent/*:: <any> */ {
/*:: client: ApolloClient; */
static async getInitialProps (config/*: Object */) {
const { Component, router, ctx } = config
const props = {
...(app.getInitialProps ? await app.getInitialProps(config) : {}),
...(await getProps(ctx))
}
const client = getClient(props, ctx)
if (isNode) {
try {
await getDataFromTree(
createElement(app, { ...props, Component, router, client })
)
} catch (error) {
console.error('Error while running `getDataFromTree`', error)
}
Head.rewind()
}
return { ...props, cache: client.cache.extract() }
}
constructor (props/*: Object */) {
super(props)
this.client = getClient(props)
}
render () {
return createElement(app, { ...this.props, client: this.client })
}
}
module.exports = nextApollo