Insert.ts 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. import { FieldObject } from '@server/types';
  2. import { generateId } from './Common';
  3. import { DataTypeEnum } from '@/consts'
  4. /**
  5. * function to convert uploaded csv to AttuGrid component accepted data type
  6. * @param data uploaded csv data, e.g. [['name1', 12], ['name2', 14]]
  7. * @returns key value pair object array, use index as key, e.g. [{0: 'name1', 1: 12}, {0: 'name2', 1: 14}]
  8. */
  9. export const transferCsvArrayToTableData = (data: any[][]) => {
  10. return data.reduce(
  11. (result, arr) => [...result, { ...arr, id: generateId() }],
  12. []
  13. );
  14. };
  15. /**
  16. * function to replace object key
  17. * @param obj e.g. {0: 'name1', 1: 12, 2: 'red'}
  18. * @param newKeys e.g. ['name', 'age', 'color']
  19. * @returns e.g. {name: 'name1', age: 12, color: 'red'}
  20. */
  21. const replaceKeysByIndex = (
  22. obj: any,
  23. newKeys: string[],
  24. fields: FieldObject[]
  25. ) => {
  26. const keyValues = Object.keys(obj).map(key => {
  27. const newKey = newKeys[Number(key)] || key;
  28. const field = fields.find(f => f.name === newKey);
  29. const isVarChar = field && field.dataType === DataTypeEnum.VarChar as any;
  30. return { [newKey]: isVarChar? obj[key] : parseValue(obj[key]) };
  31. });
  32. return Object.assign({}, ...keyValues);
  33. };
  34. export const parseValue = (value: string) => {
  35. try {
  36. return JSON.parse(value);
  37. } catch (err) {
  38. return value;
  39. }
  40. };
  41. export const formatValue = (value: any) => {
  42. if (Array.isArray(value) && value.length > 0) {
  43. return `[${value}]`;
  44. }
  45. if (typeof value === 'object' && value && !Array.isArray(value)) {
  46. return JSON.stringify(value);
  47. }
  48. return value;
  49. };
  50. /**
  51. *
  52. * @param heads table heads, e.g. ['field1', 'field2', 'field3']
  53. * @param data table data, e.g. [[23, [2,3,34,4,5,56], [1,1,1,1,1,1,1,1,1,1,1]]]
  54. * @returns key value pair object array, with user selected heads or csv heads
  55. */
  56. export const combineHeadsAndData = (
  57. heads: string[],
  58. data: any[],
  59. fields: FieldObject[]
  60. ) => {
  61. // use index as key, flatten two-dimensional array
  62. // filter useless row
  63. const flatTableData = data
  64. .filter(d => d.some((item: string) => item !== ''))
  65. .reduce((result, arr) => [...result, { ...arr }], []);
  66. // replace flatTableData key with real head rely on index
  67. return flatTableData.map((d: any) => replaceKeysByIndex(d, heads, fields));
  68. };