forked from liteflow-labs/starter-kit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.ts
77 lines (71 loc) · 2.01 KB
/
client.ts
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
import {
ApolloClient,
from,
HttpLink,
InMemoryCache,
NormalizedCacheObject,
ServerError,
} from '@apollo/client'
import { onError as linkOnError } from '@apollo/client/link/error'
const isServer = typeof window === 'undefined'
const windowApolloState = !isServer && window.__NEXT_DATA__.props.apolloState
let _client: ApolloClient<NormalizedCacheObject>
export default function getClient(
apiKey: string,
authorization: string | null,
origin: string,
forceReset = false,
onError?: (status: number) => void,
): ApolloClient<NormalizedCacheObject> {
if (_client && !forceReset) return _client
const errorLink = linkOnError(({ graphQLErrors, networkError }) => {
if (graphQLErrors)
graphQLErrors.forEach(({ message, locations, path }) =>
console.error(
`[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`,
),
)
if (!networkError) return
const { statusCode } = networkError as ServerError
if (
statusCode === 404 || // Not found
statusCode === 402 || // Payment required
statusCode >= 500 || // Server error
statusCode < 600
)
return onError?.(statusCode)
})
const httpLink = new HttpLink({
uri: `${
process.env.NEXT_PUBLIC_LITEFLOW_BASE_URL || 'https://api.liteflow.com'
}/${apiKey}/graphql`,
headers: {
...(authorization ? { authorization: `Bearer ${authorization}` } : {}),
origin,
},
})
_client = new ApolloClient({
cache: new InMemoryCache({
typePolicies: {
Account: {
keyFields: ['address'],
},
Asset: {
keyFields: ['chainId', 'collectionAddress', 'tokenId'],
},
Collection: {
keyFields: ['chainId', 'address'],
},
},
}).restore(windowApolloState || {}),
link: from([errorLink, httpLink]),
ssrMode: isServer,
defaultOptions: {
watchQuery: {
fetchPolicy: 'cache-and-network',
},
},
ssrForceFetchDelay: 100,
})
return _client
}