mirror of
https://github.com/invoke-ai/InvokeAI.git
synced 2026-02-13 22:14:59 -05:00
In the latest redux, unknown actions are typed as `unknown`. This forces type-safety upon us, requiring us to be more careful about the shape of actions. In this case, we don't know if the rejection has a payload or what shape it may be in, so we need to do runtime checks. This is implemented with a simple zod schema, but probably the right way to handle this is to have consistent types in our RTK-Query error logic.
42 lines
1.1 KiB
TypeScript
42 lines
1.1 KiB
TypeScript
import type { Middleware, MiddlewareAPI } from '@reduxjs/toolkit';
|
|
import { isRejectedWithValue } from '@reduxjs/toolkit';
|
|
import { addToast } from 'features/system/store/systemSlice';
|
|
import { t } from 'i18next';
|
|
import { z } from 'zod';
|
|
|
|
const zRejectedForbiddenAction = z.object({
|
|
action: z.object({
|
|
payload: z.object({
|
|
status: z.literal(403),
|
|
data: z.object({
|
|
detail: z.string(),
|
|
}),
|
|
}),
|
|
}),
|
|
});
|
|
|
|
export const authToastMiddleware: Middleware =
|
|
(api: MiddlewareAPI) => (next) => (action) => {
|
|
if (isRejectedWithValue(action)) {
|
|
try {
|
|
const parsed = zRejectedForbiddenAction.parse(action);
|
|
const { dispatch } = api;
|
|
const customMessage =
|
|
parsed.action.payload.data.detail !== 'Forbidden'
|
|
? parsed.action.payload.data.detail
|
|
: undefined;
|
|
dispatch(
|
|
addToast({
|
|
title: t('common.somethingWentWrong'),
|
|
status: 'error',
|
|
description: customMessage,
|
|
})
|
|
);
|
|
} catch {
|
|
// no-op
|
|
}
|
|
}
|
|
|
|
return next(action);
|
|
};
|