Form/Common: pass http errors

This commit is contained in:
vchikalkin 2024-02-02 15:25:50 +03:00
parent 08aee48f07
commit 54df128e56
2 changed files with 29 additions and 9 deletions

View File

@ -55,7 +55,7 @@ export async function save({ pageUrlParams, payload }: Input) {
.post(payload, url)
.res<boolean>((res) => res.ok)
.then((res) => res)
.catch((error: WretchError) => error.json as t.HttpValidationError);
.catch((error: WretchError) => error.json as t.HttpValidationError | t.HttpError);
}
export async function retract({ pageUrlParams, payload }: Input) {
@ -65,7 +65,7 @@ export async function retract({ pageUrlParams, payload }: Input) {
.post(payload, url)
.res<boolean>((res) => res.ok)
.then((res) => res)
.catch((error: WretchError) => error.json as t.HttpValidationError);
.catch((error: WretchError) => error.json as t.HttpValidationError | t.HttpError);
}
export async function getDocumentTypes({ pageUrlParams }: Input) {

View File

@ -6,6 +6,9 @@ import { useFormStore } from '@/store/ius/form';
import { Button } from '@repo/ui';
import { useCallback, useContext } from 'react';
const ERROR_RETRACT = 'Произошла ошибка при возврате на доработку';
const ERROR_SAVE = 'Произошла ошибка при сохранении';
export function Buttons() {
const { reset, resetValidation, setValidation, status, values } = useFormStore();
const { pageUrlParams, setFormState } = useContext(FormContext);
@ -15,14 +18,23 @@ export function Buttons() {
resetValidation();
apiIus.save({ pageUrlParams, payload: values }).then((res) => {
if (typeof res !== 'boolean') {
setTimeout(() => {
setFormState({ status: 'edit' });
}, 300);
Object.keys(res.errors).forEach((name) => {
const elementValidation = res?.errors?.[name];
const { errors } = res;
if (Array.isArray(errors)) {
setFormState({ status: 'error', text: errors?.at(0) || ERROR_SAVE });
return;
}
Object.keys(errors).forEach((name) => {
const elementValidation = errors?.[name];
if (elementValidation)
setValidation({ message: elementValidation[0] ?? '', name, valid: false });
});
setTimeout(() => {
setFormState({ status: 'edit' });
}, 300);
} else {
setFormState({ status: 'success' });
setTimeout(() => {
@ -37,11 +49,19 @@ export function Buttons() {
resetValidation();
apiIus.retract({ pageUrlParams, payload: values }).then((res) => {
if (typeof res !== 'boolean') {
const { errors } = res;
if (Array.isArray(errors)) {
setFormState({ status: 'error', text: errors?.at(0) || ERROR_RETRACT });
return;
}
setTimeout(() => {
setFormState({ status: 'edit' });
}, 300);
Object.keys(res.errors).forEach((name) => {
const elementValidation = res?.errors?.[name];
Object.keys(errors).forEach((name) => {
const elementValidation = errors?.[name];
if (elementValidation)
setValidation({ message: elementValidation[0] ?? '', name, valid: false });
});