* Processes response from the backend API. * @param {Object} response - An object as returned by `fetch` * @returns {Promise } * Success case: a JSON response with status 2xx. Promise resolves with data * from response body. * Error case: anything else, e.g. non-JSON or
(response)
| 29 | * |
| 30 | */ |
| 31 | async function processJsonResponse(response) { |
| 32 | const contentType = response.headers.get("content-type") || ""; |
| 33 | if (!contentType.includes("application/json")) { |
| 34 | const status = `${response.status} ${response.statusText}`; |
| 35 | const bodyText = await response.text(); |
| 36 | throw new ControllerError( |
| 37 | "Malformed API response, content type must be JSON.\n" + |
| 38 | `Response status: ${status}\n\n${bodyText}` |
| 39 | ); |
| 40 | } |
| 41 | |
| 42 | let jsonBody; |
| 43 | try { |
| 44 | jsonBody = await response.json(); |
| 45 | } catch (jsonParseError) { |
| 46 | throw new ControllerError( |
| 47 | "Malformed API response, JSON body cannot be parsed.\n" + jsonParseError |
| 48 | ); |
| 49 | } |
| 50 | |
| 51 | // Resolve on 2xx response: |
| 52 | if (response.status >= 200 && response.status < 300) { |
| 53 | return jsonBody; |
| 54 | } |
| 55 | // Reject otherwise: |
| 56 | throw new ControllerError( |
| 57 | jsonBody.message || "Unknown error: " + JSON.stringify(jsonBody), |
| 58 | jsonBody.code |
| 59 | ); |
| 60 | } |
| 61 | |
| 62 | export async function getLatestRelease() { |
| 63 | return fetch("/api/latestRelease", { |