Conservation de l'état connecté entre 2 rafraichissement de page
L'état de connexion est conservé dans le sessionStorage et réutilisé par défaut lors du rafraichissement de la page. Si une erreur 401 survient lors d'un appel à l'API alors l'utilisateur est redirigé vers la page d'accueil.
This commit is contained in:
74
client/src/util/apollo.ts
Normal file
74
client/src/util/apollo.ts
Normal file
@ -0,0 +1,74 @@
|
||||
|
||||
import { ApolloClient, InMemoryCache, HttpLink, from } from '@apollo/client';
|
||||
import { Config } from '../config';
|
||||
import { WebSocketLink } from "@apollo/client/link/ws";
|
||||
import { RetryLink } from "@apollo/client/link/retry";
|
||||
import { onError } from "@apollo/client/link/error";
|
||||
import { SubscriptionClient } from "subscriptions-transport-ws";
|
||||
import { User } from '../types/user';
|
||||
|
||||
export function createClient(setLoggedIn: (boolean) => void) {
|
||||
const subscriptionClient = new SubscriptionClient(Config.subscriptionEndpoint, {
|
||||
reconnect: true,
|
||||
});
|
||||
|
||||
const errorLink = onError(({ operation }) => {
|
||||
const { response } = operation.getContext();
|
||||
if (response.status === 401) setLoggedIn(false);
|
||||
});
|
||||
|
||||
const retryLink = new RetryLink({attempts: {max: 2}}).split(
|
||||
(operation) => operation.operationName === 'subscription',
|
||||
new WebSocketLink(subscriptionClient),
|
||||
new HttpLink({
|
||||
uri: Config.graphQLEndpoint,
|
||||
credentials: 'include',
|
||||
})
|
||||
);
|
||||
|
||||
const cache = new InMemoryCache({
|
||||
typePolicies: {
|
||||
Workgroup: {
|
||||
fields: {
|
||||
members: {
|
||||
merge: mergeArrayByField<User>("id"),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return new ApolloClient<any>({
|
||||
cache: cache,
|
||||
link: from([
|
||||
errorLink,
|
||||
retryLink
|
||||
]),
|
||||
});
|
||||
}
|
||||
|
||||
export function mergeArrayByField<T>(fieldName: string) {
|
||||
return (existing: T[] = [], incoming: T[], { readField, mergeObjects }) => {
|
||||
const merged: any[] = existing ? existing.slice(0) : [];
|
||||
|
||||
const objectFieldToIndex: Record<string, number> = Object.create(null);
|
||||
if (existing) {
|
||||
existing.forEach((obj, index) => {
|
||||
objectFieldToIndex[readField(fieldName, obj)] = index;
|
||||
});
|
||||
}
|
||||
|
||||
incoming.forEach(obj => {
|
||||
const field = readField(fieldName, obj);
|
||||
const index = objectFieldToIndex[field];
|
||||
if (typeof index === "number") {
|
||||
merged[index] = mergeObjects(merged[index], obj);
|
||||
} else {
|
||||
objectFieldToIndex[name] = merged.length;
|
||||
merged.push(obj);
|
||||
}
|
||||
});
|
||||
|
||||
return merged;
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user