Created
October 24, 2017 07:42
-
-
Save zapkub/9d4610fde549dd5dae5a7db86581cbfb to your computer and use it in GitHub Desktop.
apollo-with-ssr-user-session
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react' | |
import { ApolloProvider, getDataFromTree } from 'react-apollo' | |
import 'isomorphic-fetch' | |
import { sessionQuery } from './withSession' | |
import apolloClientFactory from '../../common/apolloClientFactory' | |
export default (Component) => class withData extends React.Component { | |
static async getInitialProps (context) { | |
if (typeof window === 'undefined') { | |
const props = { | |
user: context.req.user, | |
query: context.query | |
} | |
const getInitialPropsFromComponent = async () => { | |
if (Component.getInitialProps) { | |
const componentProps = await Component.getInitialProps(context) | |
return { | |
...componentProps, | |
...props | |
} | |
} else return props | |
} | |
const endpoint = `http://localhost:${process.env.PORT || 3000}/graphql` | |
const componentProps = await getInitialPropsFromComponent() | |
const client = apolloClientFactory.createNewClient(endpoint, true) | |
const query = context.query | |
const app = ( | |
<ApolloProvider client={client}> | |
<Component query={query} {...componentProps} /> | |
</ApolloProvider>) | |
// get user profile if session available | |
if (props.user) { | |
client.writeQuery({ | |
query: sessionQuery, | |
data: { | |
me: { | |
_id: props.user._id.toString(), | |
name: props.user.name, | |
email: props.user.email, | |
facebookID: props.user.facebookID, | |
username: props.user.username, | |
__typename: 'users' | |
} | |
} | |
}) | |
} | |
await getDataFromTree(app) | |
const initState = client.getInitialState() | |
return { | |
...componentProps, | |
query, | |
initState | |
} | |
} else { | |
console.log('appstart', context) | |
return { | |
query: context.query | |
} | |
} | |
} | |
constructor (props) { | |
super(props) | |
if (typeof window !== 'undefined') { | |
console.log(props.initState) | |
if (!window.client) { | |
window.client = apolloClientFactory.createNewClient('/graphql', false, props.initState) | |
} | |
this.client = window.client | |
} else { | |
this.client = apolloClientFactory.createNewClient(`http://localhost:${process.env.port || 3000}/graphql`, true, props.initState) | |
} | |
} | |
render () { | |
return ( | |
<ApolloProvider client={this.client}> | |
<Component {...this.props} /> | |
</ApolloProvider> | |
) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment