-
-
Notifications
You must be signed in to change notification settings - Fork 629
Expand file tree
/
Copy pathapolloClient.ts
More file actions
65 lines (56 loc) · 1.6 KB
/
apolloClient.ts
File metadata and controls
65 lines (56 loc) · 1.6 KB
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
import { ApolloClient, InMemoryCache, HttpLink } from '@apollo/client'
import { setContext } from '@apollo/client/link/context'
import { AppError, handleAppError } from 'app/global-error'
import { GRAPHQL_URL } from 'utils/env.client'
import { getCsrfToken } from 'utils/utility'
let hasShownGraphQLConnectionError = false
const notifyGraphQLConnectionError = () => {
if (hasShownGraphQLConnectionError) {
return
}
hasShownGraphQLConnectionError = true
handleAppError(
new AppError(
500,
'Unable to reach the GraphQL backend. Ensure the backend service is running and NEXT_PUBLIC_GRAPHQL_URL points to a valid /graphql/ endpoint.'
),
{ timeout: 12000 }
)
}
const createApolloClient = () => {
if (!GRAPHQL_URL) {
const error = new AppError(
500,
'Missing NEXT_PUBLIC_GRAPHQL_URL. Set it in frontend/.env and ensure the backend GraphQL service is running.'
)
handleAppError(error)
return null
}
const httpLink = new HttpLink({
credentials: 'include',
fetch: async (uri, options) => {
try {
return await fetch(uri, options)
} catch (error) {
notifyGraphQLConnectionError()
throw error
}
},
uri: GRAPHQL_URL,
})
const authLink = setContext(async (_, { headers }) => {
const csrfToken = await getCsrfToken()
return {
headers: {
...headers,
'X-CSRFToken': csrfToken || '',
},
}
})
return new ApolloClient({
cache: new InMemoryCache(),
link: authLink.concat(httpLink),
})
}
const apolloClient = createApolloClient()
export default apolloClient