Files
InvokeAI/invokeai/frontend/web/src/services/api/authToastMiddleware.ts
psychedelicious ca07449fb4 fix(ui): add typeguard for action.payload
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.
2023-12-09 16:09:26 +11:00

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);
};