/
index.tsx
393 lines (344 loc) · 12.5 KB
/
index.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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
import type {
ApolloClientOptions,
setLogVerbosity,
ApolloCache,
} from '@apollo/client'
import * as apolloClient from '@apollo/client'
import { setContext } from '@apollo/client/link/context'
import { createPersistedQueryLink } from '@apollo/client/link/persisted-queries'
import { getMainDefinition } from '@apollo/client/utilities'
import { fetch as crossFetch } from '@whatwg-node/fetch'
import { print } from 'graphql/language/printer'
// Note: Importing directly from `apollo/client` doesn't work properly in Storybook.
const {
ApolloProvider,
ApolloClient,
ApolloLink,
HttpLink,
InMemoryCache,
useQuery,
useMutation,
useSubscription,
useBackgroundQuery,
useReadQuery,
useSuspenseQuery,
setLogVerbosity: apolloSetLogVerbosity,
} = apolloClient
import type { UseAuth } from '@redwoodjs/auth'
import { useNoAuth } from '@redwoodjs/auth'
import './typeOverride'
import {
FetchConfigProvider,
useFetchConfig,
} from '../components/FetchConfigProvider'
import { GraphQLHooksProvider } from '../components/GraphQLHooksProvider'
import {
fragmentRegistry,
registerFragment,
registerFragments,
} from './fragmentRegistry'
import { SSELink } from './sseLink'
import { useCache } from './useCache'
export type {
CacheKey,
FragmentIdentifier,
RegisterFragmentResult,
} from './fragmentRegistry'
export { useCache }
export { fragmentRegistry, registerFragment, registerFragments }
export type ApolloClientCacheConfig = apolloClient.InMemoryCacheConfig
export type RedwoodApolloLinkName =
| 'withToken'
| 'authMiddleware'
| 'updateDataApolloLink'
| 'httpLink'
export type RedwoodApolloLink<
Name extends RedwoodApolloLinkName,
Link extends apolloClient.ApolloLink = apolloClient.ApolloLink
> = {
name: Name
link: Link
}
export type RedwoodApolloLinks = [
RedwoodApolloLink<'withToken'>,
RedwoodApolloLink<'authMiddleware'>,
RedwoodApolloLink<'updateDataApolloLink'>,
RedwoodApolloLink<'httpLink', apolloClient.ApolloLink | apolloClient.HttpLink>
]
export type RedwoodApolloLinkFactory = (
links: RedwoodApolloLinks
) => apolloClient.ApolloLink
export type GraphQLClientConfigProp = Omit<
ApolloClientOptions<unknown>,
'cache' | 'link'
> & {
cache?: ApolloCache<unknown>
/**
* Configuration for Apollo Client's `InMemoryCache`.
* See https://www.apollographql.com/docs/react/caching/cache-configuration/.
*/
cacheConfig?: ApolloClientCacheConfig
/**
* Configuration for the terminating `HttpLink`.
* See https://www.apollographql.com/docs/react/api/link/apollo-link-http/#httplink-constructor-options.
*
* For example, you can use this prop to set the credentials policy so that cookies can be sent to other domains:
*
* ```js
* <RedwoodApolloProvider graphQLClientConfig={{
* httpLinkConfig: { credentials: 'include' }
* }}>
* ```
*/
httpLinkConfig?: apolloClient.HttpOptions
/**
* Extend or overwrite `RedwoodApolloProvider`'s Apollo Link.
*
* To overwrite Redwood's Apollo Link, just provide your own `ApolloLink`.
*
* To extend Redwood's Apollo Link, provide a function—it'll get passed an array of Redwood's Apollo Links
* which are objects with a name and link property:
*
* ```js
* const link = (redwoodApolloLinks) => {
* const consoleLink = new ApolloLink((operation, forward) => {
* console.log(operation.operationName)
* return forward(operation)
* })
*
* return ApolloLink.from([consoleLink, ...redwoodApolloLinks.map(({ link }) => link)])
* }
* ```
*
* If you do this, there's a few things you should keep in mind:
* - your function should return a single link (e.g., using `ApolloLink.from`; see https://www.apollographql.com/docs/react/api/link/introduction/#additive-composition)
* - the `HttpLink` should come last (https://www.apollographql.com/docs/react/api/link/introduction/#the-terminating-link)
*/
link?: apolloClient.ApolloLink | RedwoodApolloLinkFactory
}
const ApolloProviderWithFetchConfig: React.FunctionComponent<{
config: Omit<GraphQLClientConfigProp, 'cacheConfig' | 'cache'> & {
cache: ApolloCache<unknown>
}
useAuth?: UseAuth
logLevel: ReturnType<typeof setLogVerbosity>
children: React.ReactNode
}> = ({ config, children, useAuth = useNoAuth, logLevel }) => {
// Should they run into it, this helps users with the "Cannot render cell; GraphQL success but data is null" error.
// See https://github.com/redwoodjs/redwood/issues/2473.
apolloSetLogVerbosity(logLevel)
// Here we're using Apollo Link to customize Apollo Client's data flow.
// Although we're sending conventional HTTP-based requests and could just pass `uri` instead of `link`,
// we need to fetch a new token on every request, making middleware a good fit for this.
//
// See https://www.apollographql.com/docs/react/api/link/introduction.
const { getToken, type: authProviderType } = useAuth()
// `updateDataApolloLink` keeps track of the most recent req/res data so they can be passed to
// any errors passed up to an error boundary.
type ApolloRequestData = {
mostRecentRequest?: {
operationName?: string
operationKind?: string
variables?: Record<string, unknown>
query?: string
}
mostRecentResponse?: any
}
const data = {
mostRecentRequest: undefined,
mostRecentResponse: undefined,
} as ApolloRequestData
const updateDataApolloLink = new ApolloLink((operation, forward) => {
const { operationName, query, variables } = operation
data.mostRecentRequest = {}
data.mostRecentRequest.operationName = operationName
data.mostRecentRequest.operationKind = query?.kind.toString()
data.mostRecentRequest.variables = variables
data.mostRecentRequest.query = query && print(operation.query)
return forward(operation).map((result) => {
data.mostRecentResponse = result
return result
})
})
const withToken = setContext(async () => {
const token = await getToken()
return { token }
})
const { headers, uri } = useFetchConfig()
const authMiddleware = new ApolloLink((operation, forward) => {
const { token } = operation.getContext()
// Only add auth headers when there's a token. `token` is `null` when `!isAuthenticated`.
const authHeaders = token
? {
'auth-provider': authProviderType,
authorization: `Bearer ${token}`,
}
: {}
operation.setContext(() => ({
headers: {
...operation.getContext().headers,
...headers,
// Duped auth headers, because we may remove the `FetchConfigProvider` at a later date.
...authHeaders,
},
}))
return forward(operation)
})
const { httpLinkConfig, link: redwoodApolloLink, ...rest } = config ?? {}
// A terminating link. Apollo Client uses this to send GraphQL operations to a server over HTTP.
// See https://www.apollographql.com/docs/react/api/link/introduction/#the-terminating-link.
let httpLink = new HttpLink({ uri, ...httpLinkConfig })
if (globalThis.RWJS_EXP_STREAMING_SSR) {
httpLink = new HttpLink({ uri, fetch: crossFetch, ...httpLinkConfig })
}
// Our terminating link needs to be smart enough to handle subscriptions, and if the GraphQL query
// is subscription it needs to use the SSELink (server sent events link).
const httpOrSSELink =
typeof SSELink !== 'undefined'
? apolloClient.split(
({ query }) => {
const definition = getMainDefinition(query)
return (
definition.kind === 'OperationDefinition' &&
definition.operation === 'subscription'
)
},
new SSELink({
url: uri,
auth: { authProviderType, tokenFn: getToken },
httpLinkConfig,
headers,
}),
httpLink
)
: httpLink
/**
* Use Trusted Documents aka Persisted Operations aka Queries
*
* When detecting a meta hash, Apollo Client will send the hash from the document and not the query itself.
*
* You must configure your GraphQL server to support this feature with the useTrustedDocuments option.
*
* See https://www.apollographql.com/docs/react/api/link/persisted-queries/
*/
interface DocumentNodeWithMeta extends apolloClient.DocumentNode {
__meta__?: {
hash: string
}
}
// Check if the query made includes the hash, and if so then make the request with the persisted query link
const terminatingLink = apolloClient.split(
({ query }) => {
const documentQuery = query as DocumentNodeWithMeta
return documentQuery?.['__meta__']?.['hash'] !== undefined
},
createPersistedQueryLink({
generateHash: (document: any) => document['__meta__']['hash'],
}).concat(httpOrSSELink),
httpOrSSELink
)
// The order here is important. The last link *must* be a terminating link like HttpLink, SSELink, or the PersistedQueryLink.
const redwoodApolloLinks: RedwoodApolloLinks = [
{ name: 'withToken', link: withToken },
{ name: 'authMiddleware', link: authMiddleware },
{ name: 'updateDataApolloLink', link: updateDataApolloLink },
{ name: 'httpLink', link: terminatingLink },
]
let link = redwoodApolloLink
link ??= ApolloLink.from(redwoodApolloLinks.map((l) => l.link))
if (typeof link === 'function') {
link = link(redwoodApolloLinks)
}
const client = new ApolloClient({
// Default options for every Cell. Better to specify them here than in `beforeQuery` where it's too easy to overwrite them.
// See https://www.apollographql.com/docs/react/api/core/ApolloClient/#example-defaultoptions-object.
defaultOptions: {
watchQuery: {
// The `fetchPolicy` we expect:
//
// > Apollo Client executes the full query against both the cache and your GraphQL server.
// > The query automatically updates if the result of the server-side query modifies cached fields.
//
// See https://www.apollographql.com/docs/react/data/queries/#cache-and-network.
fetchPolicy: 'cache-and-network',
// So that Cells rerender when refetching.
// See https://www.apollographql.com/docs/react/data/queries/#inspecting-loading-states.
notifyOnNetworkStatusChange: true,
},
},
link,
...rest,
})
const extendErrorAndRethrow = (error: any, _errorInfo: React.ErrorInfo) => {
error['mostRecentRequest'] = data.mostRecentRequest
error['mostRecentResponse'] = data.mostRecentResponse
throw error
}
return (
<ApolloProvider client={client}>
<ErrorBoundary onError={extendErrorAndRethrow}>{children}</ErrorBoundary>
</ApolloProvider>
)
}
type ComponentDidCatch = React.ComponentLifecycle<any, any>['componentDidCatch']
interface ErrorBoundaryProps {
error?: unknown
onError: NonNullable<ComponentDidCatch>
children: React.ReactNode
}
class ErrorBoundary extends React.Component<ErrorBoundaryProps> {
componentDidCatch(...args: Parameters<NonNullable<ComponentDidCatch>>) {
this.setState({})
this.props.onError(...args)
}
render() {
return this.props.children
}
}
export const RedwoodApolloProvider: React.FunctionComponent<{
graphQLClientConfig?: GraphQLClientConfigProp
fragments?: apolloClient.DocumentNode[]
useAuth?: UseAuth
logLevel?: ReturnType<typeof setLogVerbosity>
children: React.ReactNode
}> = ({
graphQLClientConfig,
fragments,
useAuth = useNoAuth,
logLevel = 'debug',
children,
}) => {
// Since Apollo Client gets re-instantiated on auth changes,
// we have to instantiate `InMemoryCache` here, so that it doesn't get wiped.
const { cacheConfig, ...config } = graphQLClientConfig ?? {}
// Auto register fragments
if (fragments) {
fragmentRegistry.register(...fragments)
}
const cache = new InMemoryCache({
fragments: fragmentRegistry,
possibleTypes: cacheConfig?.possibleTypes,
...cacheConfig,
}).restore(globalThis?.__REDWOOD__APOLLO_STATE ?? {})
return (
<FetchConfigProvider useAuth={useAuth}>
<ApolloProviderWithFetchConfig
// This order so that the user can still completely overwrite the cache.
config={{ cache, ...config }}
useAuth={useAuth}
logLevel={logLevel}
>
<GraphQLHooksProvider
useQuery={useQuery}
useMutation={useMutation}
useSubscription={useSubscription}
useBackgroundQuery={useBackgroundQuery}
useReadQuery={useReadQuery}
useSuspenseQuery={useSuspenseQuery}
>
{children}
</GraphQLHooksProvider>
</ApolloProviderWithFetchConfig>
</FetchConfigProvider>
)
}