refactor(frontend): content logic

This commit is contained in:
yassinedorbozgithub 2024-10-03 16:35:40 +01:00
parent 7c74348001
commit 3258781d5f

View File

@ -119,6 +119,20 @@ const ContentFieldInput: React.FC<ContentFieldInput> = ({
return <Input {...field} error={!!errors[contentField.name]} />; return <Input {...field} error={!!errors[contentField.name]} />;
} }
}; };
const INITIAL_FIELDS = ["title", "status"];
const buildDynamicFields = (
content: IContentAttributes,
contentType?: IContentType,
) => ({
title: content.title,
entity: content.entity,
status: content.status,
dynamicFields: {
...contentType?.fields
?.filter(({ name }) => !INITIAL_FIELDS.includes(name))
.reduce((acc, { name }) => ({ ...acc, [name]: content[name] }), {}),
},
});
export type ContentDialogProps = DialogControlProps<{ export type ContentDialogProps = DialogControlProps<{
content?: IContent; content?: IContent;
@ -163,7 +177,7 @@ export const ContentDialog: FC<ContentDialogProps> = ({
const onSubmitForm = async (params: IContentAttributes) => { const onSubmitForm = async (params: IContentAttributes) => {
if (content) { if (content) {
updateContent( updateContent(
{ id: content.id, params }, { id: content.id, params: buildDynamicFields(params, contentType) },
{ {
onError: () => { onError: () => {
toast.error(t("message.internal_server_error")); toast.error(t("message.internal_server_error"));
@ -176,7 +190,7 @@ export const ContentDialog: FC<ContentDialogProps> = ({
); );
} else if (contentType) { } else if (contentType) {
createContent( createContent(
{ ...params, entity: contentType.id }, { ...buildDynamicFields(params, contentType), entity: contentType.id },
{ {
onError: (error) => { onError: (error) => {
toast.error(error); toast.error(error);
@ -198,11 +212,7 @@ export const ContentDialog: FC<ContentDialogProps> = ({
useEffect(() => { useEffect(() => {
if (content) { if (content) {
reset({ reset(content);
entity: content.entity,
status: content.status,
title: content.title,
});
} else { } else {
reset(); reset();
} }
@ -221,7 +231,11 @@ export const ContentDialog: FC<ContentDialogProps> = ({
<Controller <Controller
name={contentField.name} name={contentField.name}
control={control} control={control}
defaultValue={content ? content[contentField.name] : null} defaultValue={
content
? content?.["dynamicFields"]?.[contentField.name]
: null
}
rules={ rules={
contentField.name === "title" contentField.name === "title"
? validationRules.title ? validationRules.title