2017-01-16 14:27:58 +02:00
|
|
|
import { showLoading, hideLoading } from 'react-redux-loading-bar';
|
2023-05-10 13:59:29 +03:00
|
|
|
import type { AnyAction, Middleware } from 'redux';
|
|
|
|
|
|
|
|
import type { RootState } from '..';
|
2017-01-16 14:27:58 +02:00
|
|
|
|
2023-05-09 17:56:26 +03:00
|
|
|
interface Config {
|
2023-05-09 20:02:12 +03:00
|
|
|
promiseTypeSuffixes?: string[];
|
2023-05-09 17:56:26 +03:00
|
|
|
}
|
|
|
|
|
2023-05-09 20:02:12 +03:00
|
|
|
const defaultTypeSuffixes: Config['promiseTypeSuffixes'] = [
|
|
|
|
'PENDING',
|
|
|
|
'FULFILLED',
|
|
|
|
'REJECTED',
|
|
|
|
];
|
2017-01-16 14:27:58 +02:00
|
|
|
|
2023-05-09 20:02:12 +03:00
|
|
|
export const loadingBarMiddleware = (
|
2023-07-13 12:26:45 +03:00
|
|
|
config: Config = {},
|
2023-05-09 20:02:12 +03:00
|
|
|
): Middleware<Record<string, never>, RootState> => {
|
2023-07-13 12:49:16 +03:00
|
|
|
const promiseTypeSuffixes = config.promiseTypeSuffixes ?? defaultTypeSuffixes;
|
2017-01-16 14:27:58 +02:00
|
|
|
|
2023-05-09 20:02:12 +03:00
|
|
|
return ({ dispatch }) =>
|
|
|
|
(next) =>
|
2023-05-10 13:59:29 +03:00
|
|
|
(action: AnyAction) => {
|
2023-05-09 20:02:12 +03:00
|
|
|
if (action.type && !action.skipLoading) {
|
|
|
|
const [PENDING, FULFILLED, REJECTED] = promiseTypeSuffixes;
|
2017-01-16 14:27:58 +02:00
|
|
|
|
2023-05-09 20:02:12 +03:00
|
|
|
const isPending = new RegExp(`${PENDING}$`, 'g');
|
|
|
|
const isFulfilled = new RegExp(`${FULFILLED}$`, 'g');
|
|
|
|
const isRejected = new RegExp(`${REJECTED}$`, 'g');
|
2017-01-16 14:27:58 +02:00
|
|
|
|
2023-05-10 13:59:29 +03:00
|
|
|
if (typeof action.type === 'string') {
|
|
|
|
if (action.type.match(isPending)) {
|
|
|
|
dispatch(showLoading());
|
|
|
|
} else if (
|
2023-07-13 12:49:16 +03:00
|
|
|
action.type.match(isFulfilled) ??
|
2023-05-10 13:59:29 +03:00
|
|
|
action.type.match(isRejected)
|
|
|
|
) {
|
|
|
|
dispatch(hideLoading());
|
|
|
|
}
|
2023-05-09 20:02:12 +03:00
|
|
|
}
|
2017-01-16 14:27:58 +02:00
|
|
|
}
|
|
|
|
|
2023-05-09 20:02:12 +03:00
|
|
|
return next(action);
|
|
|
|
};
|
2023-05-09 17:56:26 +03:00
|
|
|
};
|