mirror of
https://github.com/invoke-ai/InvokeAI
synced 2024-08-30 20:32:17 +00:00
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.
This commit is contained in:
parent
fb39f621c6
commit
ca07449fb4
@ -1,16 +1,29 @@
|
||||
import type { Middleware, MiddlewareAPI } from '@reduxjs/toolkit';
|
||||
import { isRejectedWithValue } from '@reduxjs/toolkit';
|
||||
import type { MiddlewareAPI, Middleware } 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)) {
|
||||
if (action.payload.status === 403) {
|
||||
try {
|
||||
const parsed = zRejectedForbiddenAction.parse(action);
|
||||
const { dispatch } = api;
|
||||
const customMessage =
|
||||
action.payload.data.detail !== 'Forbidden'
|
||||
? action.payload.data.detail
|
||||
parsed.action.payload.data.detail !== 'Forbidden'
|
||||
? parsed.action.payload.data.detail
|
||||
: undefined;
|
||||
dispatch(
|
||||
addToast({
|
||||
@ -19,6 +32,8 @@ export const authToastMiddleware: Middleware =
|
||||
description: customMessage,
|
||||
})
|
||||
);
|
||||
} catch {
|
||||
// no-op
|
||||
}
|
||||
}
|
||||
|
||||
|
Loading…
Reference in New Issue
Block a user