2020-07-23 13:37:39 +00:00
|
|
|
import { setContext } from "apollo-link-context";
|
|
|
|
import { ErrorResponse, onError } from "apollo-link-error";
|
|
|
|
|
|
|
|
import { getTokens, removeTokens } from "./";
|
|
|
|
import { isJwtError, JWTError } from "./errors";
|
|
|
|
|
|
|
|
interface ResponseError extends ErrorResponse {
|
|
|
|
networkError?: Error & {
|
|
|
|
statusCode?: number;
|
|
|
|
bodyText?: string;
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
2020-07-24 09:17:25 +00:00
|
|
|
export const invalidateTokenLink = onError((error: ResponseError) => {
|
2020-07-23 13:37:39 +00:00
|
|
|
if (
|
|
|
|
(error.networkError && error.networkError.statusCode === 401) ||
|
|
|
|
error.graphQLErrors?.some(isJwtError)
|
|
|
|
) {
|
|
|
|
if (error.graphQLErrors[0].extensions.code !== JWTError.expired) {
|
|
|
|
removeTokens();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
|
|
|
export const tokenLink = setContext((_, context) => {
|
|
|
|
const authToken = getTokens().auth;
|
|
|
|
|
|
|
|
return {
|
|
|
|
...context,
|
|
|
|
headers: {
|
|
|
|
...context.headers,
|
2021-06-29 09:00:44 +00:00
|
|
|
"Authorization-Bearer": authToken || null
|
2020-07-23 13:37:39 +00:00
|
|
|
}
|
|
|
|
};
|
|
|
|
});
|
|
|
|
|
2020-07-24 09:17:25 +00:00
|
|
|
const link = invalidateTokenLink.concat(tokenLink);
|
2020-07-23 13:37:39 +00:00
|
|
|
|
|
|
|
export default link;
|