Created
April 25, 2018 14:47
-
-
Save stolinski/91bd1633eb5ce07305cd8e6eecf78da7 to your computer and use it in GitHub Desktop.
Apollo Meteor SSR
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 { StaticRouter } from 'react-router'; | |
import { ServerStyleSheet } from 'styled-components'; | |
import { onPageLoad } from 'meteor/server-render'; | |
// import { createApolloServer } from './apolloServer'; | |
import { createApolloServer } from 'meteor/apollo'; | |
import { Helmet } from 'react-helmet'; | |
import { SchemaLink } from 'apollo-link-schema'; | |
import 'isomorphic-fetch'; | |
// Apollo | |
import { ApolloProvider, renderToStringWithData } from 'react-apollo'; | |
import { ApolloClient } from 'apollo-client'; | |
import { InMemoryCache } from 'apollo-cache-inmemory'; | |
import { withClientState } from 'apollo-link-state'; | |
import { from } from 'apollo-link'; | |
// App Utils | |
import App from 'imports/ui/layouts/App'; | |
import { schema } from './register-api'; | |
import defaultState from '../both/defaultState'; | |
import stateMutations from '../both/stateMutations'; | |
const render = async sink => { | |
try { | |
const cache = new InMemoryCache(); | |
const stateLink = withClientState({ | |
cache, | |
resolvers: stateMutations, | |
defaults: defaultState, | |
}); | |
const schemaLink = new SchemaLink({ schema }); | |
const link = from([stateLink, schemaLink]); | |
const client = new ApolloClient({ | |
ssrMode: true, | |
link, | |
cache, | |
}); | |
const context = {}; | |
const ServerApp = ( | |
<ApolloProvider client={client}> | |
<StaticRouter location={sink.request.url} context={context}> | |
<App /> | |
</StaticRouter> | |
</ApolloProvider> | |
); | |
const content = await renderToStringWithData(ServerApp); | |
// Loads Meta | |
const meta = Helmet.renderStatic(); | |
sink.appendToHead(meta.title.toString()); | |
// Loads styles | |
const sheet = new ServerStyleSheet(); | |
sink.appendToHead(sheet.getStyleTags()); | |
// const body = renderToNodeStream(<ServerApp />); | |
sink.renderIntoElementById('app', content); | |
sink.appendToBody(` | |
<script> | |
window.__APOLLO_STATE__=${JSON.stringify(client.extract())}; | |
</script> | |
`); | |
} catch (e) { | |
console.log(e.message); | |
} | |
}; | |
onPageLoad(render); | |
// expose graphql endpoint | |
createApolloServer({ schema }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment