-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapollo.ts
97 lines (84 loc) · 2.19 KB
/
apollo.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
import { ApolloClient, InMemoryCache, makeVar, split } from '@apollo/client'
import { onError } from '@apollo/client/link/error'
import { setContext } from '@apollo/client/link/context'
import {
getMainDefinition,
offsetLimitPagination,
} from '@apollo/client/utilities'
import AsyncStorage from '@react-native-async-storage/async-storage'
import { createUploadLink } from 'apollo-upload-client'
import { WebSocketLink } from '@apollo/client/link/ws'
export const isLoggedInVar = makeVar(false)
export const tokenVar = makeVar('')
const TOKEN = 'token'
export const logUserIn = async (token: string) => {
await AsyncStorage.setItem(TOKEN, token)
isLoggedInVar(true)
tokenVar(token)
}
export const logUserOut = async () => {
await AsyncStorage.removeItem(TOKEN)
isLoggedInVar(false)
tokenVar('')
}
const uploadHttpLink = createUploadLink({
uri: 'http://fd1cac6e8a8a.ngrok.io/graphql',
})
const wsLink = new WebSocketLink({
uri: 'ws://localhost:4000/graphql',
options: {
reconnect: true,
connectionParams: () => ({
Authorization: tokenVar(),
}),
},
})
const authLink = setContext((_, { headers }) => {
return {
headers: {
...headers,
Authorization: tokenVar(),
},
}
})
const onErrorLink = onError(({ graphQLErrors, networkError }) => {
if (graphQLErrors) {
console.log(`GraphQL Error`, graphQLErrors)
}
if (networkError) {
console.log('Network Error', networkError)
}
})
export const cache = new InMemoryCache({
typePolicies: {
Query: {
fields: {
//하단 상단 같은 동작의 코드
seeFeed: offsetLimitPagination(),
// seeFeed: {
// keyArgs: false,
// merge(existing = [], incoming = []) {
// return [...existing, ...incoming]
// },
// },
},
},
},
})
const httpLinks = authLink.concat(onErrorLink).concat(uploadHttpLink)
const splitLink = split(
({ query }) => {
const definition = getMainDefinition(query)
return (
definition.kind === 'OperationDefinition' &&
definition.operation === 'subscription'
)
},
wsLink,
httpLinks
)
const client = new ApolloClient({
link: splitLink,
cache,
})
export default client