adapters.ts 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. import { get, forEach, set, isNil } from 'lodash-es';
  2. import { ModuleData, ShowStyle } from './types';
  3. /** 将原本的 formData 格式化为 api.saveOrUpdate 需要的格式 */
  4. export function parseFormDataToParams(formData: Record<string, number | string | undefined>) {
  5. const params = {};
  6. forEach(formData, (v: string | undefined, k) => {
  7. if (!v) return;
  8. return set(params, k, v);
  9. });
  10. return params;
  11. }
  12. /** 将 api.list 返回的数据格式化,格式化之后可以支持对应的表单使用,该方法会修改源数据 */
  13. export function parseModuleData(listData: { moduleData: ModuleData; showStyle: ShowStyle }) {
  14. forEach(listData.showStyle, (v, k) => {
  15. listData[`showStyle.${k}`] = v;
  16. });
  17. return listData;
  18. }
  19. /** 根据配置中的 formatter 将文本格式并返回 */
  20. export function getFormattedText(data: any, formatter: string, defaultValue?: any): string {
  21. // e.g. 'pre${prop[0].name}suf' => ['pre${prop[0].name}suf', 'prop[0].name']
  22. const exp = /\$\{([\w|\.|\[|\]]*)\}/g;
  23. const res = exp.exec(formatter);
  24. if (!res) return formatter;
  25. const [__, prop] = res;
  26. const val = defaultValue === undefined ? '-' : defaultValue;
  27. const txt = get(data, prop);
  28. return formatter.replace(exp, isNil(txt) ? val : txt);
  29. }
  30. /** 获取 formatter 需要取的源 prop,用于在一些不支持 formatter 的组件中使用 */
  31. export function getRawProp(formatter: string): string {
  32. // e.g. 'pre${prop[0].name}suf' => ['pre${prop[0].name}suf', 'prop[0].name']
  33. const exp = /\$\{([\w|\.|\[|\]]*)\}/g;
  34. const res = exp.exec(formatter);
  35. if (!res) return '';
  36. const [__, prop] = res;
  37. return prop;
  38. }