Skip to content

Commit

Permalink
refactor to addAxiosInterceptors function
Browse files Browse the repository at this point in the history
  • Loading branch information
huang0h committed Sep 20, 2023
1 parent 3721861 commit 1f255ad
Show file tree
Hide file tree
Showing 7 changed files with 77 additions and 154 deletions.
80 changes: 4 additions & 76 deletions src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -35,82 +35,7 @@ import history from './history';
import FAQ from './containers/faq';
import Email from './containers/email';
import AddSites from './containers/addSites';

/* TEMPORORY AXIOS FIX */
import { AxiosError, AxiosResponse } from 'axios';
import store, { LOCALSTORAGE_STATE_KEY } from './store';
import { asyncRequestIsComplete } from './utils/asyncRequest';
import { isTokenValid } from './auth/ducks/selectors';
import { refresh } from './auth/ducks/thunks';
import { AppAxiosInstance } from './api/apiClient';
import authClient from './auth/authClient';
import protectedApiClient from './api/protectedApiClient';

const userAuthenticationExtraArgs = {
authClient,
protectedApiClient,
};

const INVALID_ACCESS_TOKEN = 'Given access token is expired or invalid';

// TODO Use throughout application
export interface AppError extends Omit<AxiosError, 'response'> {
readonly response: AxiosResponse<string>;
}

export const responseErrorInterceptor = async (
error: AxiosError,
): Promise<AxiosResponse> => {
const originalRequest = {
...error.config,
_retry: true,
};

const tokens: UserAuthenticationReducerState['tokens'] =
store.getState().authenticationState.tokens;

if (
asyncRequestIsComplete(tokens) &&
error?.response?.status === 401 &&
error?.response?.data === INVALID_ACCESS_TOKEN &&
isTokenValid(tokens.result.refreshToken) &&
!(error.config as any)?._retry
) {
await refresh(tokens.result.refreshToken)(
store.dispatch,
store.getState,
userAuthenticationExtraArgs,
);
return AppAxiosInstance(originalRequest);
}
if (
asyncRequestIsComplete(tokens) &&
error?.response?.status === 401 &&
error?.response?.data === INVALID_ACCESS_TOKEN &&
!isTokenValid(tokens.result.refreshToken)
) {
await logout()(store.dispatch, store.getState, userAuthenticationExtraArgs);
localStorage.removeItem(LOCALSTORAGE_STATE_KEY);
history.go(0);
}
return Promise.reject(error);
};

AppAxiosInstance.interceptors.response.use(
(response) => response,
responseErrorInterceptor,
);

AppAxiosInstance.interceptors.request.use((config) => {
const tokens: UserAuthenticationReducerState['tokens'] =
store.getState().authenticationState.tokens;
if (asyncRequestIsComplete(tokens)) {
config.headers['X-Access-Token'] = tokens.result.accessToken;
}
return config;
});

/* end TEMPORORY AXIOS FIX */
import { addAxiosInterceptors } from './auth/axios';

const AppLayout = styled(Layout)`
min-height: 100vh;
Expand Down Expand Up @@ -163,6 +88,9 @@ export interface MapStateProps {
readonly lng: number;
}

// temp fix - adding axios interceptors here as they aren't don't get added when in auth/axios.ts
addAxiosInterceptors();

const App: React.FC = () => {
const dispatch = useDispatch();

Expand Down
136 changes: 68 additions & 68 deletions src/auth/axios.ts
Original file line number Diff line number Diff line change
@@ -1,76 +1,76 @@
// import { AxiosError, AxiosResponse } from 'axios';
// import store, { LOCALSTORAGE_STATE_KEY } from '../store';
// import { asyncRequestIsComplete } from '../utils/asyncRequest';
// import { UserAuthenticationReducerState } from './ducks/types';
// import { isTokenValid } from './ducks/selectors';
// import { logout, refresh } from './ducks/thunks';
// import { AppAxiosInstance } from '../api/apiClient';
// import authClient from './authClient';
// import protectedApiClient from '../api/protectedApiClient';
// import history from '../history';
import { AxiosError, AxiosResponse } from 'axios';
import store, { LOCALSTORAGE_STATE_KEY } from '../store';
import { asyncRequestIsComplete } from '../utils/asyncRequest';
import { UserAuthenticationReducerState } from './ducks/types';
import { isTokenValid } from './ducks/selectors';
import { logout, refresh } from './ducks/thunks';
import { AppAxiosInstance } from '../api/apiClient';
import authClient from './authClient';
import protectedApiClient from '../api/protectedApiClient';
import history from '../history';

// const userAuthenticationExtraArgs = {
// authClient,
// protectedApiClient,
// };
const userAuthenticationExtraArgs = {
authClient,
protectedApiClient,
};

// const INVALID_ACCESS_TOKEN = 'Given access token is expired or invalid';
const INVALID_ACCESS_TOKEN = 'Given access token is expired or invalid';

// // TODO Use throughout application
// export interface AppError extends Omit<AxiosError, 'response'> {
// readonly response: AxiosResponse<string>;
// }
// TODO Use throughout application
export interface AppError extends Omit<AxiosError, 'response'> {
readonly response: AxiosResponse<string>;
}

// export const responseErrorInterceptor = async (
// error: AxiosError,
// ): Promise<AxiosResponse> => {
// const originalRequest = {
// ...error.config,
// _retry: true,
// };
export const responseErrorInterceptor = async (
error: AxiosError,
): Promise<AxiosResponse> => {
const originalRequest = {
...error.config,
_retry: true,
};

// const tokens: UserAuthenticationReducerState['tokens'] =
// store.getState().authenticationState.tokens;
const tokens: UserAuthenticationReducerState['tokens'] =
store.getState().authenticationState.tokens;

// if (
// asyncRequestIsComplete(tokens) &&
// error?.response?.status === 401 &&
// error?.response?.data === INVALID_ACCESS_TOKEN &&
// isTokenValid(tokens.result.refreshToken) &&
// !(error.config as any)?._retry
// ) {
// await refresh(tokens.result.refreshToken)(
// store.dispatch,
// store.getState,
// userAuthenticationExtraArgs,
// );
// return AppAxiosInstance(originalRequest);
// }
// if (
// asyncRequestIsComplete(tokens) &&
// error?.response?.status === 401 &&
// error?.response?.data === INVALID_ACCESS_TOKEN &&
// !isTokenValid(tokens.result.refreshToken)
// ) {
// await logout()(store.dispatch, store.getState, userAuthenticationExtraArgs);
// localStorage.removeItem(LOCALSTORAGE_STATE_KEY);
// history.go(0);
// }
// return Promise.reject(error);
// };
if (
asyncRequestIsComplete(tokens) &&
error?.response?.status === 401 &&
error?.response?.data === INVALID_ACCESS_TOKEN &&
isTokenValid(tokens.result.refreshToken) &&
!(error.config as any)?._retry
) {
await refresh(tokens.result.refreshToken)(
store.dispatch,
store.getState,
userAuthenticationExtraArgs,
);
return AppAxiosInstance(originalRequest);
}
if (
asyncRequestIsComplete(tokens) &&
error?.response?.status === 401 &&
error?.response?.data === INVALID_ACCESS_TOKEN &&
!isTokenValid(tokens.result.refreshToken)
) {
await logout()(store.dispatch, store.getState, userAuthenticationExtraArgs);
localStorage.removeItem(LOCALSTORAGE_STATE_KEY);
history.go(0);
}
return Promise.reject(error);
};

// AppAxiosInstance.interceptors.response.use(
// (response) => response,
// responseErrorInterceptor,
// );
export const addAxiosInterceptors = () => {
AppAxiosInstance.interceptors.response.use(
(response) => response,
responseErrorInterceptor,
);

// AppAxiosInstance.interceptors.request.use((config) => {
// const tokens: UserAuthenticationReducerState['tokens'] =
// store.getState().authenticationState.tokens;
// if (asyncRequestIsComplete(tokens)) {
// config.headers['X-Access-Token'] = tokens.result.accessToken;
// }
// return config;
// });

export {};
AppAxiosInstance.interceptors.request.use((config) => {
const tokens: UserAuthenticationReducerState['tokens'] =
store.getState().authenticationState.tokens;
if (asyncRequestIsComplete(tokens)) {
config.headers['X-Access-Token'] = tokens.result.accessToken;
}
return config;
});
};
3 changes: 1 addition & 2 deletions src/auth/test/axios.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,7 @@ import {
import { AdminApiClientRoutes } from '../../api/protectedApiClient';
import { AxiosError } from 'axios';
import authClient from '../authClient';
// import { responseErrorInterceptor } from '../axios';
import { responseErrorInterceptor } from '../../App';
import { responseErrorInterceptor } from '../axios';
import store, { C4CState } from '../../store';
import { AsyncRequestCompleted } from '../../utils/asyncRequest';
import { generateState } from './thunks.test';
Expand Down
3 changes: 1 addition & 2 deletions src/containers/adminDashboard/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,7 @@ import { Flex } from '../../components/themedComponents';
import SignupForm from '../../components/forms/signupForm';
import { SignupFormValues } from '../../components/forms/ducks/types';
import ProtectedApiClient from '../../api/protectedApiClient';
// import { AppError } from '../../auth/axios';
import { AppError } from '../../App';
import { AppError } from '../../auth/axios';
import { getErrorMessage, n } from '../../utils/stringFormat';
import { SubmitButton } from '../../components/themedComponents';
import {
Expand Down
3 changes: 1 addition & 2 deletions src/containers/reports/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,7 @@ import {
ReturnButton,
} from '../../components/themedComponents';
import { CSVLink } from 'react-csv';
// import { AppError } from '../../auth/axios';
import { AppError } from '../../App';
import { AppError } from '../../auth/axios';
import ExportDataForm from '../../components/forms/exportDataForm';
import { Routes } from '../../App';

Expand Down
3 changes: 1 addition & 2 deletions src/utils/stringFormat.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,7 @@ import {
SiteEntryField,
} from '../containers/treePage/ducks/types';
import { NEIGHBORHOOD_IDS } from '../assets/content';
// import { AppError } from '../auth/axios';
import { AppError } from '../App';
import { AppError } from '../auth/axios';
import { Coordinate } from '../components/mapComponents/ducks/types';
import { Websites } from '../constants';
import i18n from '../i18n/i18n';
Expand Down
3 changes: 1 addition & 2 deletions src/utils/test/stringFormat.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,7 @@ import { getDateString } from '../stringFormat';
import { shortHand } from '../stringFormat';
import { SHORT_HAND_NAMES } from '../../assets/content';
import { Entry, SiteEntryFields } from '../../containers/treePage/ducks/types';
// import { AppError } from '../../auth/axios';
import { AppError } from '../../App';
import { AppError } from '../../auth/axios';
import { Websites } from '../../constants';

test('getMoneyString tests', () => {
Expand Down

0 comments on commit 1f255ad

Please sign in to comment.