import { get, forEach, set, isNil } from 'lodash-es'; import { ModuleData, ShowStyle } from './types'; /** 将原本的 formData 格式化为 api.saveOrUpdate 需要的格式 */ export function parseFormDataToParams(formData: Record) { const params = {}; forEach(formData, (v: string | undefined, k) => { if (!v) return; return set(params, k, v); }); return params; } /** 将 api.list 返回的数据格式化,格式化之后可以支持对应的表单使用,该方法会修改源数据 */ export function parseModuleData(listData: { moduleData: ModuleData; showStyle: ShowStyle }) { forEach(listData.showStyle, (v, k) => { listData[`showStyle.${k}`] = v; }); return listData; } /** 根据配置中的 formatter 将文本格式并返回 */ export function getFormattedText(data: any, formatter: string, defaultValue?: any): string { // e.g. 'pre${prop[0].name}suf' => ['pre${prop[0].name}suf', 'prop[0].name'] const exp = /\$\{([\w|\.|\[|\]]*)\}/g; const res = exp.exec(formatter); if (!res) return formatter; const [__, prop] = res; const val = defaultValue === undefined ? '-' : defaultValue; const txt = get(data, prop); return formatter.replace(exp, isNil(txt) ? val : txt); } /** 获取 formatter 需要取的源 prop,用于在一些不支持 formatter 的组件中使用 */ export function getRawProp(formatter: string): string { // e.g. 'pre${prop[0].name}suf' => ['pre${prop[0].name}suf', 'prop[0].name'] const exp = /\$\{([\w|\.|\[|\]]*)\}/g; const res = exp.exec(formatter); if (!res) return ''; const [__, prop] = res; return prop; }