1. /**
  2. * Formats API responses for validation checks with error logging.
  3. * @param {object} response The API response object.
  4. * @param {function} validate The validation function. Takes the response as input and returns true if valid, false otherwise.
  5. * @param {string} endpoint The API endpoint being checked (for logging).
  6. */
  7. function formatApiResponseAndValidate(response, validate, endpoint) {
  8. try {
  9. // Log the endpoint being checked
  10. console.log(`Validating response from endpoint: ${endpoint}`);
  11. // Format the response for readability
  12. const formattedResponse = formatResponse(response);
  13. // Validate the response
  14. const isValid = validate(formattedResponse);
  15. if (isValid) {
  16. console.log(`Validation successful for endpoint: ${endpoint}`);
  17. return formattedResponse; // Return the formatted response if valid
  18. } else {
  19. console.error(`Validation failed for endpoint: ${endpoint}`);
  20. console.error("Detailed Response:", formattedResponse); // Log the formatted response for debugging
  21. return null; // Or throw an error, depending on your error handling strategy
  22. }
  23. } catch (error) {
  24. console.error(`Error processing response from endpoint: ${endpoint}`, error);
  25. return null; // Or throw the error, depending on your error handling strategy
  26. }
  27. }
  28. /**
  29. * Formats the API response for better readability in logs/validation.
  30. * @param {object} response The raw API response.
  31. * @returns {string} The formatted response as a JSON string.
  32. */
  33. function formatResponse(response) {
  34. try {
  35. return JSON.stringify(response, null, 2); // Pretty-print JSON with indentation
  36. } catch (error) {
  37. console.error("Error formatting response:", error);
  38. return String(response); // Return the raw response if formatting fails
  39. }
  40. }
  41. // Example usage (can be removed if not needed)
  42. // const sampleResponse = {
  43. // "status": "success",
  44. // "data": {
  45. // "id": 123,
  46. // "name": "Example Item",
  47. // "value": 42
  48. // }
  49. // };
  50. // function validateResponse(response) {
  51. // // Example validation: check if 'status' is 'success' and 'data' has 'name'
  52. // return response.status === "success" && response.data && response.data.name;
  53. // }
  54. // formatApiResponseAndValidate(sampleResponse, validateResponse, "/api/items");

Add your comment