Files
ncd-fe/packages/pl-fe/src/middleware/errors.ts
nicole mikołajczyk 9f98b5b07d nicolium: oxlint and oxfmt migration, remove eslint
Signed-off-by: nicole mikołajczyk <git@mkljczk.pl>
2026-02-15 13:30:55 +01:00

36 lines
1.1 KiB
TypeScript

import toast from '@/toast';
import type { AnyAction, Middleware } from 'redux';
/** Whether the action is considered a failure. */
const isFailType = (type: string): boolean => type.endsWith('_FAIL');
/** Whether the action is a failure to fetch from browser storage. */
const isRememberFailType = (type: string): boolean => type.endsWith('_REMEMBER_FAIL');
/** Whether the error contains an Axios response. */
const hasResponse = (error: any): boolean => Boolean(error && error.response);
/** Don't show 401's. */
const authorized = (error: any): boolean => error?.response?.status !== 401;
/** Whether the error should be shown to the user. */
const shouldShowError = ({ type, skipAlert, error }: AnyAction): boolean =>
!skipAlert &&
hasResponse(error) &&
authorized(error) &&
isFailType(type) &&
!isRememberFailType(type);
/** Middleware to display Redux errors to the user. */
const errorsMiddleware = (): Middleware => () => (next) => (anyAction) => {
const action = anyAction as AnyAction;
if (shouldShowError(action)) {
toast.showAlertForError(action.error);
}
return next(action);
};
export { errorsMiddleware as default };