handler-conditions.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. import compareBlockValue from '@/utils/compare-block-value';
  2. import mustacheReplacer from '@/utils/reference-data/mustache-replacer';
  3. import testConditions from '@/utils/test-conditions';
  4. import { getBlockConnection } from '../helper';
  5. async function conditions({ data, outputs }, { prevBlockData, refData }) {
  6. if (data.conditions.length === 0) {
  7. throw new Error('conditions-empty');
  8. }
  9. let resultData = '';
  10. let isConditionMatch = false;
  11. let outputIndex = data.conditions.length + 1;
  12. const replacedValue = {};
  13. const condition = data.conditions[0];
  14. const prevData = Array.isArray(prevBlockData)
  15. ? prevBlockData[0]
  16. : prevBlockData;
  17. if (condition && condition.conditions) {
  18. const conditionPayload = {
  19. refData,
  20. activeTab: this.activeTab.id,
  21. sendMessage: (payload) =>
  22. this._sendMessageToTab({ ...payload, isBlock: false }),
  23. };
  24. for (let index = 0; index < data.conditions.length; index += 1) {
  25. const result = await testConditions(
  26. data.conditions[index].conditions,
  27. conditionPayload
  28. );
  29. Object.assign(replacedValue, result?.replacedValue || {});
  30. if (result.isMatch) {
  31. isConditionMatch = true;
  32. outputIndex = index + 1;
  33. break;
  34. }
  35. }
  36. } else {
  37. data.conditions.forEach(({ type, value, compareValue }, index) => {
  38. if (isConditionMatch) return;
  39. const firstValue = mustacheReplacer(compareValue ?? prevData, refData);
  40. const secondValue = mustacheReplacer(value, refData);
  41. Object.assign(replacedValue, firstValue.list, secondValue.list);
  42. const isMatch = compareBlockValue(
  43. type,
  44. firstValue.value,
  45. secondValue.value
  46. );
  47. if (isMatch) {
  48. resultData = value;
  49. outputIndex = index + 1;
  50. isConditionMatch = true;
  51. }
  52. });
  53. }
  54. return {
  55. replacedValue,
  56. data: resultData,
  57. nextBlockId: getBlockConnection({ outputs }, outputIndex),
  58. };
  59. }
  60. export default conditions;