1. /**
  2. * Decodes API responses with fallback logic.
  3. * @param {string} responseBody The raw response body from the API.
  4. * @param {object} decodingMap An object mapping content-type to decoding functions.
  5. * @returns {any} The decoded data, or null if decoding fails.
  6. */
  7. function decodeApiResponse(responseBody, decodingMap) {
  8. if (!responseBody) {
  9. console.warn("Response body is empty.");
  10. return null;
  11. }
  12. const contentType = responseBody.split(';')[0].split(':')[1].trim().toLowerCase(); // Extract content type
  13. if (decodingMap && decodingMap[contentType]) {
  14. try {
  15. return decodingMap[contentType](responseBody); // Use specific decoder function
  16. } catch (error) {
  17. console.error(`Decoding failed for content type ${contentType}:`, error);
  18. return null; // Fallback if specific decoder fails
  19. }
  20. } else {
  21. console.warn(`No decoder found for content type: ${contentType}`);
  22. return null; // Fallback if no decoder is defined
  23. }
  24. }
  25. /**
  26. * Example decoder functions (can be extended)
  27. */
  28. function decodeJson(body) {
  29. try {
  30. return JSON.parse(body);
  31. } catch (error) {
  32. console.error("JSON parsing error:", error);
  33. return null;
  34. }
  35. }
  36. function decodeXml(body) {
  37. try {
  38. // Implement XML parsing here (e.g., using xml2js)
  39. // For simplicity, this example just returns the body as a string.
  40. return body;
  41. } catch (error) {
  42. console.error("XML parsing error:", error);
  43. return null;
  44. }
  45. }
  46. function decodePlainText(body) {
  47. return body;
  48. }
  49. //Example usage:
  50. // const decodingMap = {
  51. // 'application/json': decodeJson,
  52. // 'application/xml': decodeXml,
  53. // 'text/plain': decodePlainText
  54. // };
  55. // const response = '{"name": "John", "age": 30}';
  56. // const decodedData = decodeApiResponse(response, decodingMap);
  57. // console.log(decodedData);
  58. // const response2 = '<root><name>Jane</name></root>';
  59. // const decodedData2 = decodeApiResponse(response2, decodingMap);
  60. // console.log(decodedData2);
  61. // const response3 = "This is plain text";
  62. // const decodedData3 = decodeApiResponse(response3, decodingMap);
  63. // console.log(decodedData3);
  64. //const response4 = null;
  65. //const decodedData4 = decodeApiResponse(response4, decodingMap);
  66. //console.log(decodedData4);

Add your comment