|
| 1 | +import { getDataFromTree } from "@apollo/react-ssr"; |
| 2 | +import { InMemoryCache, NormalizedCacheObject } from "apollo-cache-inmemory"; |
| 3 | +import { ApolloClient } from "apollo-client"; |
| 4 | +import { ApolloLink, split } from "apollo-link"; |
| 5 | +import { onError } from "apollo-link-error"; |
| 6 | +import { HttpLink } from "apollo-link-http"; |
| 7 | +import { WebSocketLink } from "apollo-link-ws"; |
| 8 | +import { getOperationAST } from "graphql"; |
| 9 | +import withApolloBase, { InitApolloOptions } from "next-with-apollo"; |
| 10 | +import React from "react"; |
| 11 | +import { SubscriptionClient } from "subscriptions-transport-ws"; |
| 12 | +import ws from "ws"; |
| 13 | + |
| 14 | +import { GraphileApolloLink } from "./GraphileApolloLink"; |
| 15 | + |
| 16 | +interface WithApolloOptions { |
| 17 | + useNext?: boolean; |
| 18 | + rootUrl?: string; |
| 19 | +} |
| 20 | + |
| 21 | +let wsClient: SubscriptionClient | null = null; |
| 22 | + |
| 23 | +export function resetWebsocketConnection(): void { |
| 24 | + if (wsClient) { |
| 25 | + wsClient.close(false, false); |
| 26 | + } |
| 27 | +} |
| 28 | + |
| 29 | +function makeServerSideLink(req: any, res: any) { |
| 30 | + return new GraphileApolloLink({ |
| 31 | + req, |
| 32 | + res, |
| 33 | + postgraphileMiddleware: req.app.get("postgraphileMiddleware"), |
| 34 | + }); |
| 35 | +} |
| 36 | + |
| 37 | +function makeClientSideLink(ROOT_URL: string) { |
| 38 | + const nextDataEl = |
| 39 | + typeof document !== "undefined" && document.getElementById("__NEXT_DATA__"); |
| 40 | + const headers = {}; |
| 41 | + if (nextDataEl && nextDataEl.textContent) { |
| 42 | + const data = JSON.parse(nextDataEl.textContent); |
| 43 | + headers["CSRF-Token"] = data.query.CSRF_TOKEN; |
| 44 | + } |
| 45 | + const httpLink = new HttpLink({ |
| 46 | + uri: `${ROOT_URL}/graphql`, |
| 47 | + credentials: |
| 48 | + process.env.NODE_ENV === "development" ? "include" : "same-origin", |
| 49 | + headers, |
| 50 | + }); |
| 51 | + wsClient = new SubscriptionClient( |
| 52 | + `${ROOT_URL.replace(/^http/, "ws")}/graphql`, |
| 53 | + { |
| 54 | + reconnect: true, |
| 55 | + }, |
| 56 | + typeof WebSocket !== "undefined" ? WebSocket : ws |
| 57 | + ); |
| 58 | + const wsLink = new WebSocketLink(wsClient); |
| 59 | + |
| 60 | + // Using the ability to split links, you can send data to each link |
| 61 | + // depending on what kind of operation is being sent. |
| 62 | + const mainLink = split( |
| 63 | + // split based on operation type |
| 64 | + ({ query, operationName }) => { |
| 65 | + const op = getOperationAST(query, operationName); |
| 66 | + return (op && op.operation === "subscription") || false; |
| 67 | + }, |
| 68 | + wsLink, |
| 69 | + httpLink |
| 70 | + ); |
| 71 | + return mainLink; |
| 72 | +} |
| 73 | + |
| 74 | +const getApolloClient = ( |
| 75 | + { initialState, ctx }: InitApolloOptions<NormalizedCacheObject>, |
| 76 | + withApolloOptions?: WithApolloOptions |
| 77 | +): ApolloClient<NormalizedCacheObject> => { |
| 78 | + const ROOT_URL = process.env.ROOT_URL || withApolloOptions?.rootUrl; |
| 79 | + if (!ROOT_URL) { |
| 80 | + throw new Error("ROOT_URL envvar is not set"); |
| 81 | + } |
| 82 | + |
| 83 | + const onErrorLink = onError(({ graphQLErrors, networkError }) => { |
| 84 | + if (graphQLErrors) |
| 85 | + graphQLErrors.map(({ message, locations, path }) => |
| 86 | + console.error( |
| 87 | + `[GraphQL error]: message: ${message}, location: ${JSON.stringify( |
| 88 | + locations |
| 89 | + )}, path: ${JSON.stringify(path)}` |
| 90 | + ) |
| 91 | + ); |
| 92 | + if (networkError) console.error(`[Network error]: ${networkError}`); |
| 93 | + }); |
| 94 | + |
| 95 | + const { req, res }: any = ctx || {}; |
| 96 | + const isServer = typeof window === "undefined"; |
| 97 | + const mainLink = |
| 98 | + isServer && req && res |
| 99 | + ? makeServerSideLink(req, res) |
| 100 | + : makeClientSideLink(ROOT_URL); |
| 101 | + |
| 102 | + const client = new ApolloClient({ |
| 103 | + link: ApolloLink.from([onErrorLink, mainLink]), |
| 104 | + cache: new InMemoryCache({ |
| 105 | + dataIdFromObject: (o) => |
| 106 | + o.__typename === "Query" |
| 107 | + ? "ROOT_QUERY" |
| 108 | + : o.id |
| 109 | + ? `${o.__typename}:${o.id}` |
| 110 | + : null, |
| 111 | + }).restore(initialState || {}), |
| 112 | + }); |
| 113 | + |
| 114 | + return client; |
| 115 | +}; |
| 116 | + |
| 117 | +const withApolloWithNext = withApolloBase(getApolloClient, { |
| 118 | + getDataFromTree, |
| 119 | +}); |
| 120 | + |
| 121 | +const withApolloWithoutNext = (Component: any, options?: WithApolloOptions) => ( |
| 122 | + props: any |
| 123 | +) => { |
| 124 | + const apollo = getApolloClient({}, options); |
| 125 | + return <Component {...props} apollo={apollo} />; |
| 126 | +}; |
| 127 | + |
| 128 | +export const withApollo = (Component: any, options?: WithApolloOptions) => |
| 129 | + options?.useNext === false |
| 130 | + ? withApolloWithoutNext(Component, options) |
| 131 | + : withApolloWithNext(Component); |
0 commit comments