2024-01-08 10:57:40 +00:00
|
|
|
import { isAction } from '@reduxjs/toolkit';
|
|
|
|
import type { Action, Middleware } from '@reduxjs/toolkit';
|
2023-05-10 10:59:29 +00:00
|
|
|
|
|
|
|
import type { RootState } from '..';
|
2023-05-09 14:56:26 +00:00
|
|
|
import { showAlertForError } from '../../actions/alerts';
|
2016-10-18 15:09:45 +00:00
|
|
|
|
|
|
|
const defaultFailSuffix = 'FAIL';
|
2024-01-08 10:57:40 +00:00
|
|
|
const isFailedAction = new RegExp(`${defaultFailSuffix}$`, 'g');
|
2016-10-18 15:09:45 +00:00
|
|
|
|
2024-01-08 10:57:40 +00:00
|
|
|
interface ActionWithMaybeAlertParams extends Action {
|
|
|
|
skipAlert?: boolean;
|
|
|
|
skipNotFound?: boolean;
|
|
|
|
error?: unknown;
|
|
|
|
}
|
|
|
|
|
|
|
|
function isActionWithmaybeAlertParams(
|
|
|
|
action: unknown,
|
|
|
|
): action is ActionWithMaybeAlertParams {
|
|
|
|
return isAction(action);
|
|
|
|
}
|
|
|
|
|
|
|
|
export const errorsMiddleware: Middleware<Record<string, never>, RootState> =
|
2023-05-09 17:02:12 +00:00
|
|
|
({ dispatch }) =>
|
|
|
|
(next) =>
|
2024-01-08 10:57:40 +00:00
|
|
|
(action) => {
|
|
|
|
if (
|
|
|
|
isActionWithmaybeAlertParams(action) &&
|
|
|
|
!action.skipAlert &&
|
|
|
|
action.type.match(isFailedAction)
|
|
|
|
) {
|
|
|
|
dispatch(showAlertForError(action.error, action.skipNotFound));
|
2016-10-18 15:09:45 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return next(action);
|
|
|
|
};
|