-
Notifications
You must be signed in to change notification settings - Fork 0
/
apollo.client.ts
99 lines (92 loc) · 2.74 KB
/
apollo.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
import { ApolloClient, gql, HttpLink, from, fromPromise } from "@apollo/client";
import { onError } from "@apollo/client/link/error";
import { cache, isAuthInVar } from "./apollo.cache";
const REFRESH_AUTH = gql`
mutation refresh {
AuthRefresh
}
`;
export const typeDefs = gql`
extend type Query {
clientIsAuth: Boolean!
clientUser: CachedUser!
}
`;
const refreshAuth = async () => {
const token = window.localStorage.getItem("refresh_token") || "";
// console.log("[refreshAuth]: triggered");
await client
.mutate({
mutation: REFRESH_AUTH,
context: { headers: { Authorization: token } },
})
.then(({ data }) => {
if (data.AuthRefresh) {
// console.log(data);
// console.log("ok");
return;
} else if (data.AuthRefresh == false) {
window.localStorage.removeItem("refresh_token");
isAuthInVar(false);
throw new Error("[AuthRefresh] Returned False");
} else {
throw new Error("[AuthRefresh] Borked");
}
});
};
const errorLink = onError(({ graphQLErrors, operation, forward }) => {
if (graphQLErrors) {
// console.log(graphQLErrors)
let authTrigger = false;
// CAUTION: EXTREMELY DELICATE
// having forward(operation) INSIDE
// of a map/foreach/etc will cause
// the observer to trigger even if not
// requested, in this case I have opted instead
// just have a trigger to execute the promise observer
// ultimately allowing me to asynchronous(ly)
// reset the authentication cookie via my own resolver
for (let i = 0; i < graphQLErrors.length; i++) {
if (graphQLErrors[i].message === "Unauthorized") {
authTrigger = true;
}
}
if (authTrigger) {
// console.log("[ErrorLink]: Triggered Authentication");
return (
fromPromise(
refreshAuth()
.then(() => {
// console.log("[refreshAuth]: Promise Catched");
isAuthInVar(true);
return forward(operation);
})
.catch((error) => {
// console.log("Error", error);
// console.log("hello?");
window.localStorage.removeItem("refresh_token");
isAuthInVar(false);
return;
})
)
// THIS MIGHT STILL BE NEEDED
/* .filter((value) => {
return Boolean(value);
}) */
.flatMap(() => {
return forward(operation);
})
);
}
}
});
const httpLink = new HttpLink({
uri: process.env.API_URI || "https://sosile.amazingefren.com/graphql",
credentials: "include",
});
const client = new ApolloClient({
cache,
link: from([errorLink, httpLink]),
typeDefs,
});
export default client;