1. /**
  2. * Converts user data formats for dry-run scenarios.
  3. *
  4. * @param {object} userData - The user data to convert.
  5. * @param {string} targetFormat - The desired target format ('json', 'csv', 'flat').
  6. * @returns {any} - The converted data, or null if the format is invalid.
  7. */
  8. function convertUserData(userData, targetFormat) {
  9. if (!userData || typeof userData !== 'object') {
  10. console.warn("Invalid user data provided.");
  11. return null;
  12. }
  13. switch (targetFormat.toLowerCase()) {
  14. case 'json':
  15. // Already JSON, no conversion needed.
  16. return userData;
  17. case 'csv':
  18. // Convert to CSV format.
  19. if (!Array.isArray(userData)) {
  20. console.warn("User data must be an array for CSV conversion.");
  21. return null;
  22. }
  23. if (userData.length === 0) return "";
  24. const headers = Object.keys(userData[0]);
  25. const csvRows = [headers.join(',')];
  26. for (const row of userData) {
  27. const values = headers.map(header => row[header] || ''); // Handle missing values
  28. csvRows.push(values.join(','));
  29. }
  30. return csvRows.join('\n');
  31. case 'flat':
  32. // Flatten the object into a single string.
  33. let flattenedString = '';
  34. for (const key in userData) {
  35. if (userData.hasOwnProperty(key)) {
  36. flattenedString += `${key}: ${userData[key]} | `;
  37. }
  38. }
  39. return flattenedString.slice(0, -3); // Remove trailing " | "
  40. default:
  41. console.warn("Invalid target format. Supported formats: json, csv, flat");
  42. return null;
  43. }
  44. }

Add your comment