reference-data.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. import { get, set } from 'object-path-immutable';
  2. import { isObject, objectHasKey, replaceMustache } from '@/utils/helper';
  3. const objectPath = { get, set };
  4. const refKeys = [
  5. { name: 'dataColumn', key: 'dataColumns' },
  6. { name: 'dataColumns', key: 'dataColumns' },
  7. ];
  8. export function parseKey(key) {
  9. /* eslint-disable-next-line */
  10. let [dataKey, path] = key.split('@');
  11. dataKey =
  12. (refKeys.find((item) => item.name === dataKey) || {}).key || dataKey;
  13. if (dataKey !== 'dataColumns') return { dataKey, path: path || '' };
  14. const pathArr = path?.split('.') ?? [];
  15. let dataPath = path;
  16. if (pathArr.length === 1) {
  17. dataPath = `0.${pathArr[0]}`;
  18. } else if (typeof +pathArr[0] !== 'number' || Number.isNaN(+pathArr[0])) {
  19. dataPath = `0.${pathArr.join('.')}`;
  20. }
  21. if (dataPath.endsWith('.')) dataPath = dataPath.slice(0, -1);
  22. return { dataKey: 'dataColumns', path: dataPath };
  23. }
  24. export function replaceMustacheHandler(match, data) {
  25. const key = match.slice(2, -2).replace(/\s/g, '');
  26. if (!key) return '';
  27. const { dataKey, path } = parseKey(key);
  28. const result = objectPath.get(data[dataKey], path) ?? match;
  29. return isObject(result) ? JSON.stringify(result) : result;
  30. }
  31. export default function (block, data) {
  32. const replaceKeys = [
  33. 'url',
  34. 'name',
  35. 'body',
  36. 'value',
  37. 'fileName',
  38. 'selector',
  39. 'prefixText',
  40. 'suffixText',
  41. ];
  42. let replacedBlock = block;
  43. replaceKeys.forEach((blockDataKey) => {
  44. if (!objectHasKey(block.data, blockDataKey)) return;
  45. const newDataValue = replaceMustache(
  46. replacedBlock.data[blockDataKey],
  47. (match) => replaceMustacheHandler(match, data)
  48. );
  49. replacedBlock = objectPath.set(
  50. replacedBlock,
  51. `data.${blockDataKey}`,
  52. newDataValue
  53. );
  54. });
  55. return replacedBlock;
  56. }