-
Notifications
You must be signed in to change notification settings - Fork 0
/
apollo.ts
82 lines (74 loc) · 1.93 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
import {
ApolloClient,
createHttpLink,
InMemoryCache,
makeVar,
} from "@apollo/client";
import AsyncStorage from "@react-native-async-storage/async-storage";
import { setContext } from "@apollo/client/link/context";
import {
offsetLimitPagination,
relayStylePagination,
} from "@apollo/client/utilities";
import { createUploadLink } from "apollo-upload-client";
import { onError } from "@apollo/client/link/error";
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: "https://nomadcoffee-henry.loca.lt/graphql",
uri: "http://localhost:4000/graphql",
});
const authLink = setContext((_, { headers }) => {
return {
headers: {
...headers,
token: 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: {
searchCoffeeShops: offsetLimitPagination(),
searchMyCoffeeShops: offsetLimitPagination(),
seeCoffeeShops: {
keyArgs: false,
merge(existing = {}, incoming = {}) {
return {
...incoming,
coffeeShops: [
...(existing.coffeeShops || []),
...incoming.coffeeShops,
],
};
},
},
},
},
},
});
const client = new ApolloClient({
link: authLink.concat(onErrorLink).concat(uploadHttpLink),
cache,
});
export default client;