2023-04-21 18:30:41 +03:00
|
|
|
import {
|
|
|
|
ApolloClient,
|
|
|
|
InMemoryCache,
|
|
|
|
Observable,
|
|
|
|
createHttpLink,
|
|
|
|
from,
|
|
|
|
} from '@apollo/client';
|
2023-04-21 15:07:02 +03:00
|
|
|
import { setContext } from '@apollo/client/link/context';
|
|
|
|
import { RestLink } from 'apollo-link-rest';
|
2023-04-21 18:30:41 +03:00
|
|
|
import { onError } from '@apollo/client/link/error';
|
2023-05-17 23:31:16 +03:00
|
|
|
import { refreshAccessToken } from './services/auth/AuthService';
|
2023-04-21 15:07:02 +03:00
|
|
|
|
|
|
|
const apiLink = createHttpLink({
|
2023-05-24 18:20:15 +03:00
|
|
|
uri: `${process.env.REACT_APP_API_URL}`,
|
2023-04-21 15:07:02 +03:00
|
|
|
});
|
|
|
|
|
|
|
|
const withAuthHeadersLink = setContext((_, { headers }) => {
|
|
|
|
const token = localStorage.getItem('accessToken');
|
|
|
|
return {
|
|
|
|
headers: {
|
|
|
|
...headers,
|
|
|
|
authorization: token ? `Bearer ${token}` : '',
|
|
|
|
},
|
|
|
|
};
|
|
|
|
});
|
|
|
|
|
2023-04-21 18:30:41 +03:00
|
|
|
const errorLink = onError(({ graphQLErrors, operation, forward }) => {
|
|
|
|
if (graphQLErrors) {
|
|
|
|
for (const err of graphQLErrors) {
|
|
|
|
switch (err.extensions.code) {
|
2023-05-26 15:00:32 +03:00
|
|
|
case 'UNAUTHENTICATED':
|
2023-04-21 18:30:41 +03:00
|
|
|
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);
|
|
|
|
}
|
|
|
|
})();
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
2023-04-21 15:07:02 +03:00
|
|
|
export const apiClient = new ApolloClient({
|
2023-04-21 18:30:41 +03:00
|
|
|
link: from([errorLink, withAuthHeadersLink, apiLink]),
|
2023-04-21 15:07:02 +03:00
|
|
|
cache: new InMemoryCache(),
|
|
|
|
});
|
|
|
|
|
|
|
|
const authLink = new RestLink({
|
|
|
|
uri: `${process.env.REACT_APP_AUTH_URL}`,
|
|
|
|
credentials: 'same-origin',
|
|
|
|
});
|
|
|
|
|
|
|
|
export const authClient = new ApolloClient({
|
|
|
|
link: authLink,
|
|
|
|
cache: new InMemoryCache(),
|
|
|
|
});
|