/**
* Transforms data records for non-production use with error logging.
* @param {Array<object>} records - An array of data records to transform.
* @param {function} transformFunction - A function to transform each record.
* @returns {Promise<Array<object>>} A promise that resolves with the transformed records or rejects with an error.
*/
async function transformRecords(records, transformFunction) {
if (!Array.isArray(records)) {
throw new Error("Records must be an array.");
}
if (typeof transformFunction !== 'function') {
throw new Error("Transform function must be a function.");
}
const transformedRecords = [];
for (let i = 0; i < records.length; i++) {
try {
const record = records[i];
if (typeof record !== 'object' || record === null) {
console.warn(`Skipping invalid record at index ${i}: Not an object.`);
continue;
}
const transformed = await transformFunction(record); //Use await for async transform functions.
if (transformed !== undefined) {
transformedRecords.push(transformed);
} else {
console.warn(`Skipping record at index ${i}: Transform function returned undefined.`);
}
} catch (error) {
console.error(`Error transforming record at index ${i}:`, error);
// Optionally, re-throw the error or handle it differently.
//throw error; // Re-throw to stop processing.
}
}
return transformedRecords;
}
export default transformRecords;
Add your comment