-
Notifications
You must be signed in to change notification settings - Fork 556
/
Copy pathwithData.js
99 lines (84 loc) · 2.95 KB
/
withData.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
91
92
93
94
95
96
97
98
99
import React from 'react';
import { ApolloProvider, getDataFromTree } from 'react-apollo';
import cookie from 'cookie';
import PropTypes from 'prop-types';
import debug from 'debug';
import initApollo from './initApollo';
const logger = debug('app:withData');
logger.log = console.log.bind(console);
function parseCookies(ctx = {}, options = {}) {
const mycookie = cookie.parse(
ctx.req && ctx.req.headers.cookie
? ctx.req.headers.cookie
: '', // document.cookie,
options,
);
logger('Parsing cookie: ', mycookie);
return mycookie;
}
export default (ComposedComponent) => {
return class WithData extends React.Component {
static displayName = `WithData(${ComposedComponent.displayName})`
static propTypes = {
serverState: PropTypes.object.isRequired,
}
static async getInitialProps(context) {
let serverState = { apollo: {} };
// Setup a server-side one-time-use apollo client for initial props and
// rendering (on server)
logger('getInitialProps with context: ', context);
const apollo = initApollo({}, {
getToken: () => parseCookies(context), // ['connect.sid'], // .token,
});
// Evaluate the composed component's getInitialProps()
let composedInitialProps = {};
if (ComposedComponent.getInitialProps) {
composedInitialProps = await ComposedComponent.getInitialProps(context, apollo);
}
// Run all GraphQL queries in the component tree
// and extract the resulting data
if (!process.browser) {
if (context.res && context.res.finished) {
// When redirecting, the response is finished.
// No point in continuing to render
return;
}
// Provide the `url` prop data in case a GraphQL query uses it
const url = { query: context.query, pathname: context.pathname };
// Run all GraphQL queries
const app = (
<ApolloProvider client={apollo}>
<ComposedComponent url={url} {...composedInitialProps} />
</ApolloProvider>
);
await getDataFromTree(app);
serverState = {
apollo: { // Make sure to only include Apollo's data state
data: apollo.cache.extract(), // Extract query data from the Apollo's store
},
};
}
return {
serverState,
...composedInitialProps,
};
}
constructor(props) {
super(props);
// Note: Apollo should never be used on the server side beyond the initial
// render within `getInitialProps()` above (since the entire prop tree
// will be initialized there), meaning the below will only ever be
// executed on the client.
this.apollo = initApollo({}, {
getToken: () => parseCookies(), // ['connect.sid'],
});
}
render() {
return (
<ApolloProvider client={this.apollo}>
<ComposedComponent {...this.props} />
</ApolloProvider>
);
}
};
};