1. /**
  2. * Data Migration Error Reporter
  3. *
  4. * @param {Array<Object>} data - Array of data entries to validate.
  5. * @param {Object} schema - Schema defining the expected data structure and types.
  6. * @returns {Array<string>} - Array of error messages. Empty if no errors.
  7. */
  8. function reportMigrationErrors(data, schema) {
  9. const errors = [];
  10. if (!Array.isArray(data)) {
  11. errors.push("Data must be an array.");
  12. return errors;
  13. }
  14. if (!schema || typeof schema !== 'object') {
  15. errors.push("Schema must be an object.");
  16. return errors;
  17. }
  18. for (let i = 0; i < data.length; i++) {
  19. const entry = data[i];
  20. if (typeof entry !== 'object' || entry === null) {
  21. errors.push(`Entry at index ${i} is not a valid object.`);
  22. continue; // Skip to the next entry
  23. }
  24. for (const key in schema) {
  25. if (schema.hasOwnProperty(key)) {
  26. const expectedType = schema[key].type;
  27. const required = schema[key].required === true;
  28. if (key === 'required' && schema[key].required === true) continue; //Skip checking required field
  29. if (expectedType === 'string' && typeof entry[key] !== 'string') {
  30. errors.push(`Entry at index ${i}, key '${key}' is not a string. Expected string, got ${typeof entry[key]}`);
  31. } else if (expectedType === 'number' && typeof entry[key] !== 'number') {
  32. errors.push(`Entry at index ${i}, key '${key}' is not a number. Expected number, got ${typeof entry[key]}`);
  33. } else if (expectedType === 'boolean' && typeof entry[key] !== 'boolean') {
  34. errors.push(`Entry at index ${i}, key '${key}' is not a boolean. Expected boolean, got ${typeof entry[key]}`);
  35. } else if (expectedType === 'array' && !Array.isArray(entry[key])) {
  36. errors.push(`Entry at index ${i}, key '${key}' is not an array. Expected array, got ${typeof entry[key]}`);
  37. } else if (expectedType === 'object' && typeof entry[key] !== 'object' || entry[key] === null) {
  38. errors.push(`Entry at index ${i}, key '${key}' is not an object. Expected object, got ${typeof entry[key]}`);
  39. }
  40. // Add more type checks as needed (e.g., date, etc.)
  41. if (required && !(key in entry) || (key in entry && entry[key] === null || entry[key] === undefined)) {
  42. errors.push(`Entry at index ${i}, key '${key}' is required but missing or null/undefined.`);
  43. }
  44. }
  45. }
  46. }
  47. return errors;
  48. }

Add your comment