2017-01-16 21:27:58 +09:00
|
|
|
import { showLoading, hideLoading } from 'react-redux-loading-bar';
|
2023-05-09 23:56:26 +09:00
|
|
|
import { Middleware } from 'redux';
|
|
|
|
import { RootState } from '..';
|
2017-01-16 21:27:58 +09:00
|
|
|
|
2023-05-09 23:56:26 +09:00
|
|
|
interface Config {
|
2023-05-10 06:41:18 +09:00
|
|
|
promiseTypeSuffixes?: string[];
|
2023-05-09 23:56:26 +09:00
|
|
|
}
|
|
|
|
|
2023-05-10 06:41:18 +09:00
|
|
|
const defaultTypeSuffixes: Config['promiseTypeSuffixes'] = [
|
|
|
|
'PENDING',
|
|
|
|
'FULFILLED',
|
|
|
|
'REJECTED',
|
|
|
|
];
|
2017-01-16 21:27:58 +09:00
|
|
|
|
2023-05-10 06:41:18 +09:00
|
|
|
export const loadingBarMiddleware = (
|
|
|
|
config: Config = {}
|
|
|
|
): Middleware<Record<string, never>, RootState> => {
|
2017-01-16 21:27:58 +09:00
|
|
|
const promiseTypeSuffixes = config.promiseTypeSuffixes || defaultTypeSuffixes;
|
|
|
|
|
2023-05-10 06:41:18 +09:00
|
|
|
return ({ dispatch }) =>
|
|
|
|
(next) =>
|
|
|
|
(action) => {
|
|
|
|
if (action.type && !action.skipLoading) {
|
|
|
|
const [PENDING, FULFILLED, REJECTED] = promiseTypeSuffixes;
|
2017-01-16 21:27:58 +09:00
|
|
|
|
2023-05-10 06:41:18 +09:00
|
|
|
const isPending = new RegExp(`${PENDING}$`, 'g');
|
|
|
|
const isFulfilled = new RegExp(`${FULFILLED}$`, 'g');
|
|
|
|
const isRejected = new RegExp(`${REJECTED}$`, 'g');
|
2017-01-16 21:27:58 +09:00
|
|
|
|
2023-05-10 06:41:18 +09:00
|
|
|
if (action.type.match(isPending)) {
|
|
|
|
dispatch(showLoading());
|
|
|
|
} else if (
|
|
|
|
action.type.match(isFulfilled) ||
|
|
|
|
action.type.match(isRejected)
|
|
|
|
) {
|
|
|
|
dispatch(hideLoading());
|
|
|
|
}
|
2017-01-16 21:27:58 +09:00
|
|
|
}
|
|
|
|
|
2023-05-10 06:41:18 +09:00
|
|
|
return next(action);
|
|
|
|
};
|
2023-05-09 23:56:26 +09:00
|
|
|
};
|