|
| 1 | +const diff = require('deep-diff'); |
| 2 | +const formatText = require('./formatText'); |
| 3 | +const formatPath = require('./formatPath'); |
| 4 | +const formatGroupedChanges = require('./formatGroupedChanges'); |
| 5 | +const enLocale = require('../locales/en.json'); |
| 6 | +const ruLocale = require('../locales/ru.json'); |
| 7 | + |
| 8 | +const locales = { |
| 9 | + en: enLocale, |
| 10 | + ru: ruLocale |
| 11 | +}; |
| 12 | + |
| 13 | +function pretifyDeepDiff(changes, options = {}) { |
| 14 | + const locale = locales[options.locale] || locales['en']; |
| 15 | + const customTexts = options.customTexts || {}; |
| 16 | + |
| 17 | + if (!changes || !Array.isArray(changes)) { |
| 18 | + return 'No changes detected.'; |
| 19 | + } |
| 20 | + |
| 21 | + const groupedChanges = { |
| 22 | + added: [], |
| 23 | + deleted: [], |
| 24 | + edited: [], |
| 25 | + arrayChange: [] |
| 26 | + }; |
| 27 | + |
| 28 | + changes.forEach(change => { |
| 29 | + switch (change.kind) { |
| 30 | + case 'N': |
| 31 | + groupedChanges.added.push(formatText(customTexts.added || locale.added, { |
| 32 | + path: formatPath(change.path), |
| 33 | + value: JSON.stringify(change.rhs) |
| 34 | + })); |
| 35 | + break; |
| 36 | + case 'D': |
| 37 | + groupedChanges.deleted.push(formatText(customTexts.deleted || locale.deleted, { |
| 38 | + path: formatPath(change.path) |
| 39 | + })); |
| 40 | + break; |
| 41 | + case 'E': |
| 42 | + groupedChanges.edited.push(formatText(customTexts.edited || locale.edited, { |
| 43 | + path: formatPath(change.path), |
| 44 | + oldValue: JSON.stringify(change.lhs), |
| 45 | + newValue: JSON.stringify(change.rhs) |
| 46 | + })); |
| 47 | + break; |
| 48 | + case 'A': |
| 49 | + const arrayChangeText = pretifyDeepDiff([change.item], options); |
| 50 | + groupedChanges.arrayChange.push(formatText(customTexts.arrayChange || locale.arrayChange, { |
| 51 | + path: formatPath(change.path), |
| 52 | + index: change.index, |
| 53 | + item: arrayChangeText |
| 54 | + })); |
| 55 | + break; |
| 56 | + default: |
| 57 | + break; |
| 58 | + } |
| 59 | + }); |
| 60 | + |
| 61 | + return formatGroupedChanges(groupedChanges, locale, customTexts); |
| 62 | +} |
| 63 | + |
| 64 | +module.exports = pretifyDeepDiff; |
0 commit comments