/**
* Indexes API response content for backward compatibility and basic input validation.
*
* @param {object} response The API response object.
* @param {object} schema A schema defining the expected data structure.
* @returns {object} An object containing the indexed data and validation results.
*/
function indexApiResponse(response, schema) {
const indexedData = {};
const validationResults = {};
// Iterate through the schema and extract/validate data from the response.
for (const field in schema) {
if (schema.hasOwnProperty(field)) {
const expectedType = schema[field].type;
const required = schema[field].required === true;
if (response && response[field] !== undefined) {
let value = response[field];
//Type conversion and validation
if (expectedType === 'string') {
value = String(value);
} else if (expectedType === 'number') {
value = Number(value);
} else if (expectedType === 'boolean') {
value = Boolean(value);
} else if (expectedType === 'array') {
if (!Array.isArray(value)) {
console.warn(`Field '${field}' expected to be an array, but received ${typeof value}`);
validationResults[field] = { valid: false, message: 'Expected array' };
}
}
indexedData[field] = value;
} else {
if (required) {
validationResults[field] = { valid: false, message: 'Required field missing' };
}
}
}
}
return { indexedData, validationResults };
}
Add your comment