Refresh token when token has expired

This commit is contained in:
Charles Bochet
2023-04-21 17:30:41 +02:00
parent 049664b98e
commit d3e9709e08
11 changed files with 174 additions and 133 deletions

View File

@ -1,6 +1,14 @@
import { ApolloClient, InMemoryCache, createHttpLink } from '@apollo/client';
import {
ApolloClient,
InMemoryCache,
Observable,
createHttpLink,
from,
} from '@apollo/client';
import { setContext } from '@apollo/client/link/context';
import { RestLink } from 'apollo-link-rest';
import { onError } from '@apollo/client/link/error';
import { refreshAccessToken } from './services/AuthService';
const apiLink = createHttpLink({
uri: `${process.env.REACT_APP_API_URL}/v1/graphql`,
@ -16,8 +24,46 @@ const withAuthHeadersLink = setContext((_, { headers }) => {
};
});
const errorLink = onError(({ graphQLErrors, operation, forward }) => {
if (graphQLErrors) {
for (const err of graphQLErrors) {
switch (err.extensions.code) {
case 'invalid-jwt':
return new Observable((observer) => {
(async () => {
try {
await refreshAccessToken();
const oldHeaders = operation.getContext().headers;
operation.setContext({
headers: {
...oldHeaders,
authorization: `Bearer ${localStorage.getItem(
'accessToken',
)}`,
},
});
const subscriber = {
next: observer.next.bind(observer),
error: observer.error.bind(observer),
complete: observer.complete.bind(observer),
};
forward(operation).subscribe(subscriber);
} catch (error) {
observer.error(error);
}
})();
});
}
}
}
});
export const apiClient = new ApolloClient({
link: withAuthHeadersLink.concat(apiLink),
link: from([errorLink, withAuthHeadersLink, apiLink]),
cache: new InMemoryCache(),
});