1. /**
  2. * Transforms data records for non-production use with error logging.
  3. * @param {Array<object>} records - An array of data records to transform.
  4. * @param {function} transformFunction - A function to transform each record.
  5. * @returns {Promise<Array<object>>} A promise that resolves with the transformed records or rejects with an error.
  6. */
  7. async function transformRecords(records, transformFunction) {
  8. if (!Array.isArray(records)) {
  9. throw new Error("Records must be an array.");
  10. }
  11. if (typeof transformFunction !== 'function') {
  12. throw new Error("Transform function must be a function.");
  13. }
  14. const transformedRecords = [];
  15. for (let i = 0; i < records.length; i++) {
  16. try {
  17. const record = records[i];
  18. if (typeof record !== 'object' || record === null) {
  19. console.warn(`Skipping invalid record at index ${i}: Not an object.`);
  20. continue;
  21. }
  22. const transformed = await transformFunction(record); //Use await for async transform functions.
  23. if (transformed !== undefined) {
  24. transformedRecords.push(transformed);
  25. } else {
  26. console.warn(`Skipping record at index ${i}: Transform function returned undefined.`);
  27. }
  28. } catch (error) {
  29. console.error(`Error transforming record at index ${i}:`, error);
  30. // Optionally, re-throw the error or handle it differently.
  31. //throw error; // Re-throw to stop processing.
  32. }
  33. }
  34. return transformedRecords;
  35. }
  36. export default transformRecords;

Add your comment