Commit 1045cd4c authored by Henrik Wenz's avatar Henrik Wenz Committed by Luis Alvarez D

Refactor api-routes-apollo-server-and-client example (#8673)

* Remove connectToDevTools in favour of better default

Disabled devtools in production

* Refactor api-routes-apollo-server-and-client example
parent 9731e7e9
import React, { useMemo } from 'react'
import Head from 'next/head'
import { ApolloProvider } from '@apollo/react-hooks'
import { ApolloClient } from 'apollo-client'
import { InMemoryCache } from 'apollo-cache-inmemory'
let apolloClient = null
/**
* Creates and provides the apolloContext
* to a next.js PageTree. Use it by wrapping
* your PageComponent via HOC pattern.
* @param {Function|Class} PageComponent
* @param {Object} [config]
* @param {Boolean} [config.ssr=true]
*/
export function withApollo (PageComponent, { ssr = true } = {}) {
const WithApollo = ({ apolloClient, apolloState, ...pageProps }) => {
const client = useMemo(
() => apolloClient || initApolloClient(apolloState),
[]
)
return (
<ApolloProvider client={client}>
<PageComponent {...pageProps} />
</ApolloProvider>
)
}
// Set the correct displayName in development
if (process.env.NODE_ENV !== 'production') {
const displayName =
PageComponent.displayName || PageComponent.name || 'Component'
if (displayName === 'App') {
console.warn('This withApollo HOC only works with PageComponents.')
}
WithApollo.displayName = `withApollo(${displayName})`
}
if (ssr || PageComponent.getInitialProps) {
WithApollo.getInitialProps = async ctx => {
const { AppTree } = ctx
// Initialize ApolloClient, add it to the ctx object so
// we can use it in `PageComponent.getInitialProp`.
const apolloClient = (ctx.apolloClient = initApolloClient())
// Run wrapped getInitialProps methods
let pageProps = {}
if (PageComponent.getInitialProps) {
pageProps = await PageComponent.getInitialProps(ctx)
}
// Only on the server:
if (typeof window === 'undefined') {
// When redirecting, the response is finished.
// No point in continuing to render
if (ctx.res && ctx.res.finished) {
return pageProps
}
// Only if ssr is enabled
if (ssr) {
try {
// Run all GraphQL queries
const { getDataFromTree } = await import('@apollo/react-ssr')
await getDataFromTree(
<AppTree
pageProps={{
...pageProps,
apolloClient
}}
/>
)
} catch (error) {
// Prevent Apollo Client GraphQL errors from crashing SSR.
// Handle them in components via the data.error prop:
// https://www.apollographql.com/docs/react/api/react-apollo.html#graphql-query-data-error
console.error('Error while running `getDataFromTree`', error)
}
// getDataFromTree does not call componentWillUnmount
// head side effect therefore need to be cleared manually
Head.rewind()
}
}
// Extract query data from the Apollo store
const apolloState = apolloClient.cache.extract()
return {
...pageProps,
apolloState
}
}
}
return WithApollo
}
/**
* Always creates a new apollo client on the server
* Creates or reuses apollo client in the browser.
* @param {Object} initialState
*/
function initApolloClient (initialState) {
// Make sure to create a new client for every server-side request so that data
// isn't shared between connections (which would be bad)
if (typeof window === 'undefined') {
return createApolloClient(initialState)
}
// Reuse client on the client-side
if (!apolloClient) {
apolloClient = createApolloClient(initialState)
}
return apolloClient
}
/**
* Creates and configures the ApolloClient
* @param {Object} [initialState={}]
*/
function createApolloClient (initialState = {}) {
const ssrMode = typeof window === 'undefined'
const cache = new InMemoryCache().restore(initialState)
// Check out https://github.com/zeit/next.js/pull/4611 if you want to use the AWSAppSyncClient
return new ApolloClient({
ssrMode,
link: createIsomorphLink(),
cache
})
}
function createIsomorphLink () {
if (typeof window === 'undefined') {
const { SchemaLink } = require('apollo-link-schema')
const { schema } = require('./schema')
return new SchemaLink({ schema })
} else {
const { HttpLink } = require('apollo-link-http')
return new HttpLink({
uri: '/api/graphql',
credentials: 'same-origin'
})
}
}
export const resolvers = { export const resolvers = {
Query: { Query: {
viewer (_parent, _args, _context, _info) { viewer (_parent, _args, _context, _info) {
return { name: 'John Smith', id: 1 } return { id: 1, name: 'John Smith', status: 'cached' }
} }
} }
} }
...@@ -4,6 +4,7 @@ export const typeDefs = gql` ...@@ -4,6 +4,7 @@ export const typeDefs = gql`
type User { type User {
id: ID! id: ID!
name: String! name: String!
status: String!
} }
type Query { type Query {
......
import ApolloClient from 'apollo-client'
import { SchemaLink } from 'apollo-link-schema'
import { InMemoryCache } from 'apollo-cache-inmemory'
import { HttpLink } from 'apollo-link-http'
import { schema } from '../apollo/schema'
import gql from 'graphql-tag'
let apolloClient = null
function create (initialState) {
// Check out https://github.com/zeit/next.js/pull/4611 if you want to use the AWSAppSyncClient
const isBrowser = typeof window !== 'undefined'
const link = isBrowser
? new HttpLink({
uri: '/api/graphql',
credentials: 'same-origin'
})
: new SchemaLink({ schema })
const cache = new InMemoryCache().restore(initialState || {})
return new ApolloClient({
connectToDevTools: isBrowser,
ssrMode: !isBrowser, // Disables forceFetch on the server (so queries are only run once)
link,
typeDefs: gql`
extend type User {
status: String!
}
`,
resolvers: {
User: {
status () {
return 'cached'
}
}
},
cache
})
}
export default function initApollo (initialState) {
// Make sure to create a new client for every server-side request so that data
// isn't shared between connections (which would be bad)
if (typeof window === 'undefined') {
return create(initialState)
}
// Reuse client on the client-side
if (!apolloClient) {
apolloClient = create(initialState)
}
return apolloClient
}
import React from 'react'
import initApollo from './init-apollo'
import Head from 'next/head'
import { getDataFromTree } from '@apollo/react-ssr'
import { ApolloProvider } from '@apollo/react-hooks'
export default App => {
return class Apollo extends React.Component {
static displayName = 'withApollo(App)'
static async getInitialProps (ctx) {
const { AppTree } = ctx
let appProps = {}
// Run all GraphQL queries in the component tree
// and extract the resulting data
const client = initApollo()
if (App.getInitialProps) {
ctx.client = client
appProps = await App.getInitialProps(ctx)
}
if (typeof window === 'undefined') {
try {
// Run all GraphQL queries
await getDataFromTree(
<ApolloProvider client={client}>
<AppTree {...appProps} />
</ApolloProvider>
)
} catch (error) {
// Prevent Apollo Client GraphQL errors from crashing SSR.
// Handle them in components via the data.error prop:
// https://www.apollographql.com/docs/react/api/react-apollo.html#graphql-query-data-error
console.error('Error while running `getDataFromTree`', error)
}
// getDataFromTree does not call componentWillUnmount
// head side effect therefore need to be cleared manually
Head.rewind()
}
// Extract query data from the Apollo store
const apolloState = client.cache.extract()
return {
...appProps,
apolloState
}
}
client = initApollo(this.props.apolloState)
render () {
return (
<ApolloProvider client={this.client}>
<App {...this.props} />
</ApolloProvider>
)
}
}
}
import withApolloClient from '../lib/with-apollo-client' import { withApollo } from '../apollo/client'
import gql from 'graphql-tag' import gql from 'graphql-tag'
import Link from 'next/link' import Link from 'next/link'
import { useQuery } from '@apollo/react-hooks' import { useQuery } from '@apollo/react-hooks'
...@@ -8,7 +8,7 @@ const ViewerQuery = gql` ...@@ -8,7 +8,7 @@ const ViewerQuery = gql`
viewer { viewer {
id id
name name
status @client status
} }
} }
` `
...@@ -33,8 +33,4 @@ const Index = () => { ...@@ -33,8 +33,4 @@ const Index = () => {
return null return null
} }
Index.getInitialProps = async ({ client }) => { export default withApollo(Index)
await client.query({ query: ViewerQuery })
}
export default withApolloClient(Index)
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment