| 1 | import { exportaAHtml } from "./exportaAHtml.js" | 
  | 2 | import { ProblemDetails } from "./ProblemDetails.js" | 
  | 3 |  | 
  | 4 |  | 
  | 5 |  | 
  | 6 |  | 
  | 7 |  | 
  | 8 |  | 
  | 9 |  | 
  | 10 |  | 
  | 11 |  | 
  | 12 | export async function consumeJson(servicio) { | 
  | 13 |  | 
  | 14 |  if (typeof servicio === "string") { | 
  | 15 |   servicio = fetch(servicio, { | 
  | 16 |    headers: { "Accept": "application/json, application/problem+json" } | 
  | 17 |   }) | 
  | 18 |  } else if (!(servicio instanceof Promise)) { | 
  | 19 |   throw new Error("Servicio de tipo incorrecto.") | 
  | 20 |  } | 
  | 21 |  | 
  | 22 |  const respuesta = await servicio | 
  | 23 |  | 
  | 24 |  const headers = respuesta.headers | 
  | 25 |  | 
  | 26 |  if (respuesta.ok) { | 
  | 27 |    | 
  | 28 |  | 
  | 29 |   if (respuesta.status === 204) { | 
  | 30 |     | 
  | 31 |  | 
  | 32 |    return { headers, body: {} } | 
  | 33 |  | 
  | 34 |   } else { | 
  | 35 |  | 
  | 36 |    const texto = await respuesta.text() | 
  | 37 |  | 
  | 38 |    try { | 
  | 39 |  | 
  | 40 |     return { headers, body: JSON.parse(texto) } | 
  | 41 |  | 
  | 42 |    } catch (error) { | 
  | 43 |  | 
  | 44 |      | 
  | 45 |     throw new ProblemDetails(respuesta.status, headers, texto, | 
  | 46 |      "/error/errorinterno.html") | 
  | 47 |  | 
  | 48 |    } | 
  | 49 |  | 
  | 50 |   } | 
  | 51 |  | 
  | 52 |  } else { | 
  | 53 |    | 
  | 54 |  | 
  | 55 |   const texto = await respuesta.text() | 
  | 56 |  | 
  | 57 |   if (texto === "") { | 
  | 58 |  | 
  | 59 |     | 
  | 60 |    throw new ProblemDetails(respuesta.status, headers, respuesta.statusText) | 
  | 61 |  | 
  | 62 |   } else { | 
  | 63 |     | 
  | 64 |  | 
  | 65 |    try { | 
  | 66 |  | 
  | 67 |     const { title, type, detail } = JSON.parse(texto) | 
  | 68 |  | 
  | 69 |     throw new ProblemDetails(respuesta.status, headers, | 
  | 70 |      typeof title === "string" ? title : respuesta.statusText, | 
  | 71 |      typeof type === "string" ? type : undefined, | 
  | 72 |      typeof detail === "string" ? detail : undefined) | 
  | 73 |  | 
  | 74 |    } catch (error) { | 
  | 75 |  | 
  | 76 |     if (error instanceof ProblemDetails) { | 
  | 77 |       | 
  | 78 |  | 
  | 79 |      throw error | 
  | 80 |  | 
  | 81 |     } else { | 
  | 82 |  | 
  | 83 |      throw new ProblemDetails(respuesta.status, headers, respuesta.statusText, | 
  | 84 |       undefined, texto) | 
  | 85 |  | 
  | 86 |     } | 
  | 87 |  | 
  | 88 |    } | 
  | 89 |  | 
  | 90 |   } | 
  | 91 |  | 
  | 92 |  } | 
  | 93 |  | 
  | 94 | } | 
  | 95 |  | 
  | 96 | exportaAHtml(consumeJson) |