Last active
February 3, 2018 18:07
-
-
Save stolinski/e8428eefadf4274759ab6a73b41d0eda to your computer and use it in GitHub Desktop.
Not working SSR Config GraphQL & Meteor
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 { renderToNodeStream } from 'react-dom/server'; | |
import { StaticRouter } from 'react-router'; | |
import { ServerStyleSheet } from 'styled-components'; | |
import { onPageLoad } from 'meteor/server-render'; | |
import { Helmet } from 'react-helmet'; | |
import 'isomorphic-fetch'; | |
// Apollo | |
import { ApolloProvider, getDataFromTree } from 'react-apollo'; | |
import { ApolloClient, Observable } from 'apollo-client'; | |
import { ApolloLink } from 'apollo-link'; | |
import { graphql } from 'graphql'; | |
import { print } from 'graphql/language/printer'; | |
// import { HttpLink } from 'apollo-link-http'; | |
import { InMemoryCache } from 'apollo-cache-inmemory'; | |
import { createApolloServer } from './createApolloServer'; | |
// App Utils | |
import App from 'imports/ui/layouts/App'; | |
import { schema } from './register-api'; | |
const render = async sink => { | |
const client = new ApolloClient({ | |
ssrMode: true, | |
// simple local interface to query graphql directly | |
link: new ApolloLink( | |
({ query, variables, operationName }) => | |
new Observable(obs => { | |
graphql(schema, print(query), {}, {}, variables, operationName) | |
.then(result => { | |
obs.next(result); | |
obs.complete(); | |
}) | |
.catch(obs.error.bind(obs)); | |
}) | |
), | |
cache: new InMemoryCache(), | |
}); | |
const context = {}; | |
const ServerApp = props => ( | |
<ApolloProvider client={client}> | |
<StaticRouter location={props.location} context={context}> | |
<App /> | |
</StaticRouter> | |
</ApolloProvider> | |
); | |
// load all data from local server; | |
await getDataFromTree(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 location={sink.request.url} />); | |
sink.renderIntoElementById('app', body); | |
sink.appendToBody(` | |
<script> | |
window.__APOLLO_STATE__=${JSON.stringify(client.extract())}; | |
</script> | |
`); | |
}; | |
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