-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapollo-client.ts
More file actions
80 lines (66 loc) · 2.41 KB
/
apollo-client.ts
File metadata and controls
80 lines (66 loc) · 2.41 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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import { ApolloClient, InMemoryCache, split } from '@apollo/client/core';
import createUploadLink from 'apollo-upload-client/createUploadLink.mjs';
import { ApolloLink } from '@apollo/client/core';
import { GraphQLWsLink } from '@apollo/client/link/subscriptions';
import { createClient } from 'graphql-ws';
import { getMainDefinition } from '@apollo/client/utilities';
import { detectAuth, removeAuth } from './src/shared/modules/auth';
import { getRouter } from './src/shared/modules/router';
import { onError } from '@apollo/client/link/error';
import { reactive } from 'vue';
import { Toast } from "./src/shared/modules/toast";
import { i18n } from "./src/shared/plugins/i18n";
const errorLink = onError(({ graphQLErrors, networkError }) => {
if (graphQLErrors) {
graphQLErrors.forEach(({ message }) => {
if (message.includes("not authenticated")) {
const auth = reactive(detectAuth());
const router = getRouter();
const currentPath = router.currentRoute.value?.fullPath;
const loginLocation: { name: string; query?: { next: string } } = { name: 'auth.login' };
if (currentPath && currentPath.startsWith('/')) {
loginLocation.query = { next: currentPath };
}
removeAuth(auth);
router.push(loginLocation);
}
});
}
if (networkError) {
if (networkError.message.includes('Failed to fetch')) {
// @ts-ignore global is working fine and is documented but we get and error like it's missing
const message = i18n.global.t('network.error');
Toast.error(message);
}
}
});
// HTTP link for queries and mutations
const httpLink = createUploadLink({
uri: import.meta.env.VITE_APP_API_GRAPHQL_URL,
credentials: 'include',
});
// WebSocket link for subscriptions
const wsLink = new GraphQLWsLink(
createClient({
url: import.meta.env.VITE_APP_API_GRAPHQL_WEBSOCKET_URL,
})
);
// Using split to direct subscription operations to wsLink and others to httpLink
const splitLink = split(
({ query }) => {
const definition = getMainDefinition(query);
return (
definition.kind === 'OperationDefinition' &&
definition.operation === 'subscription'
);
},
wsLink,
httpLink,
);
const combinedLink = ApolloLink.from([errorLink, splitLink]);
const cache = new InMemoryCache();
const apolloClient = new ApolloClient({
link: combinedLink,
cache,
});
export default apolloClient;