1. /**
  2. * Indexes API response content for backward compatibility and basic input validation.
  3. *
  4. * @param {object} response The API response object.
  5. * @param {object} schema A schema defining the expected data structure.
  6. * @returns {object} An object containing the indexed data and validation results.
  7. */
  8. function indexApiResponse(response, schema) {
  9. const indexedData = {};
  10. const validationResults = {};
  11. // Iterate through the schema and extract/validate data from the response.
  12. for (const field in schema) {
  13. if (schema.hasOwnProperty(field)) {
  14. const expectedType = schema[field].type;
  15. const required = schema[field].required === true;
  16. if (response && response[field] !== undefined) {
  17. let value = response[field];
  18. //Type conversion and validation
  19. if (expectedType === 'string') {
  20. value = String(value);
  21. } else if (expectedType === 'number') {
  22. value = Number(value);
  23. } else if (expectedType === 'boolean') {
  24. value = Boolean(value);
  25. } else if (expectedType === 'array') {
  26. if (!Array.isArray(value)) {
  27. console.warn(`Field '${field}' expected to be an array, but received ${typeof value}`);
  28. validationResults[field] = { valid: false, message: 'Expected array' };
  29. }
  30. }
  31. indexedData[field] = value;
  32. } else {
  33. if (required) {
  34. validationResults[field] = { valid: false, message: 'Required field missing' };
  35. }
  36. }
  37. }
  38. }
  39. return { indexedData, validationResults };
  40. }

Add your comment