/**
* Formats API responses for validation checks with error logging.
* @param {object} response The API response object.
* @param {function} validate The validation function. Takes the response as input and returns true if valid, false otherwise.
* @param {string} endpoint The API endpoint being checked (for logging).
*/
function formatApiResponseAndValidate(response, validate, endpoint) {
try {
// Log the endpoint being checked
console.log(`Validating response from endpoint: ${endpoint}`);
// Format the response for readability
const formattedResponse = formatResponse(response);
// Validate the response
const isValid = validate(formattedResponse);
if (isValid) {
console.log(`Validation successful for endpoint: ${endpoint}`);
return formattedResponse; // Return the formatted response if valid
} else {
console.error(`Validation failed for endpoint: ${endpoint}`);
console.error("Detailed Response:", formattedResponse); // Log the formatted response for debugging
return null; // Or throw an error, depending on your error handling strategy
}
} catch (error) {
console.error(`Error processing response from endpoint: ${endpoint}`, error);
return null; // Or throw the error, depending on your error handling strategy
}
}
/**
* Formats the API response for better readability in logs/validation.
* @param {object} response The raw API response.
* @returns {string} The formatted response as a JSON string.
*/
function formatResponse(response) {
try {
return JSON.stringify(response, null, 2); // Pretty-print JSON with indentation
} catch (error) {
console.error("Error formatting response:", error);
return String(response); // Return the raw response if formatting fails
}
}
// Example usage (can be removed if not needed)
// const sampleResponse = {
// "status": "success",
// "data": {
// "id": 123,
// "name": "Example Item",
// "value": 42
// }
// };
// function validateResponse(response) {
// // Example validation: check if 'status' is 'success' and 'data' has 'name'
// return response.status === "success" && response.data && response.data.name;
// }
// formatApiResponseAndValidate(sampleResponse, validateResponse, "/api/items");
Add your comment