-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathwithApollo.tsx
57 lines (52 loc) · 1.87 KB
/
withApollo.tsx
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
/**
* Component inspired by next-with-apollo, with an extended API
*
* - you can pass "ssr: true" instead of directly passing "getDataFromTree"
* - you can change the graphqlUri
*/
import withApollo, { WithApolloOptions } from "next-with-apollo";
import createApolloClient from "./apolloClient";
import { NextPage } from "next";
// Uncomment for v3 API
//import {
// ApolloProvider,
// NormalizedCacheObject
//} from "@apollo/client";
import { ApolloProvider } from "@apollo/react-hooks";
import { NormalizedCacheObject } from "apollo-cache-inmemory";
import { getDataFromTree as getDataFromTreeDefault } from "@apollo/react-ssr";
// support the same options as next-with-apollo, but also additional client config + ssr activation
export interface VulcanWithApolloOptions extends WithApolloOptions {
graphqlUri?: string;
ssr?: boolean;
}
const defaultOptions: Partial<VulcanWithApolloOptions> = {
graphqlUri: process.env.NEXT_PUBLIC_GRAPHQL_URI,
ssr: true,
};
const initApolloClient = (graphqlUri: string) => ({ initialState, ctx }) => {
return createApolloClient(graphqlUri, initialState, ctx);
};
const renderWithApolloProvider = ({ Page, props }) => {
return (
<ApolloProvider client={props.apollo}>
<Page {...props} />
</ApolloProvider>
);
};
const vulcanWithApollo = (Page: NextPage, options: VulcanWithApolloOptions = {}) => {
const mergedOptions = { ...defaultOptions, ...options };
const {
graphqlUri,
ssr,
getDataFromTree: getDataFromTreeFromOptions,
render: renderFromOption,
} = mergedOptions;
const getDataFromTree =
getDataFromTreeFromOptions || (ssr && getDataFromTreeDefault);
const withApolloOptions = { getDataFromTree, renderFromOption };
return withApollo<NormalizedCacheObject>(initApolloClient(graphqlUri), {
render: renderWithApolloProvider,
})(Page, withApolloOptions);
};
export default vulcanWithApollo;