/
SOFG1
/
hasida
Обзор
Документация
Войти
/
SOFG1
/
hasida
Код
Запросы
0
Задачи
Пакеты
0
Релизы
0
Аналитика
Безопасность
master
src/utils/convertFormData.ts
109 строк
3 KB
Eddy
initial commit
22 июл 2024, 17:14
22 июл 2024, 17:14
b43c0d0
Код
Авторство
О чём код?
import { IField } from "../api/user"; import { IsraelCountryCode, incomeOptions } from "../constants"; import getFormatDate from "./getFormatDate"; //Converts field inputs data (single values) and single dropdowns const convertFormData = (formData: { [key: string]: any }, fields: IField[] | undefined) => { const requestData: { [key: string]: any } = {}; fields?.forEach((k) => { const value = formData[k.name]; if (!value) { requestData[k.name] = null; return; } if (value instanceof Date) { requestData[k.name] = getFormatDate(value); return; } if (Array.isArray(value) && k.name === "education") { const valueFiltered = value.filter(v => v.institution?.id || v.education_level || v.filed_of_study); requestData[k.name] = valueFiltered.map(v => ({ ...v, institution: v.institution?.id })); return; } if (Array.isArray(value) && value) { requestData[k.name] = value.map(v => v?.value ? v.value : v ) return; } if (typeof value === "object" && value) { requestData[k.name] = value.value; return; } if (typeof value === "boolean") { requestData[k.name] = value; return; } if (value == Number(value)) { requestData[k.name] = Number(value); return; } if (value !== undefined) { requestData[k.name] = value; return; } }); return requestData; }; const convertApiData = (fields: IField[], data: { [key: string]: any }) => { const convertedData: { [key: string]: any } = {}; fields.forEach((f) => { if (!data[f.name]) return; if (f.type === "Date") { convertedData[f.name] = new Date(data[f.name]); return; } //text inputs if (f.type === "String" && !f.options.length) { convertedData[f.name] = data[f.name]; return; } //Textareas if (f.type === "Text") { convertedData[f.name] = data[f.name]; return; } //Exception for income if (f.name === "income" && data?.country?.id === IsraelCountryCode) { const opt = incomeOptions[IsraelCountryCode].find(o => o.value === data[f.name]) convertedData[f.name] = opt return } //Dropdowns if (f.type === "String" && f.options.length) { convertedData[f.name] = { label: data[f.name], value: data[f.name] }; return; } //Fetchable dropdowns if (f.type === "ForeignKey") { convertedData[f.name] = { label: data[f.name].name, value: data[f.name].id, }; return; } //Dropdowns if (f.type === "Integer") { convertedData[f.name] = data[f.name]; return; } //Array with options if (f.type === "JSONField") { convertedData[f.name] = data[f.name]; return; } //Radio button if (f.type === "Boolean") { convertedData[f.name] = data[f.name]; return; } //Dropdowns with several options if (f.type === "Many2Many") { convertedData[f.name] = data[f.name].map((d: string) => ({label: d, value: d})); return; } }); return convertedData; }; export { convertFormData, convertApiData };