From 2d016af82f751cb74314ea72ac8e247dfee11b6c Mon Sep 17 00:00:00 2001 From: Julian Lam Date: Tue, 11 Jul 2023 11:03:00 -0400 Subject: [PATCH] feat: simplified api module handler logic, content-type detection/parsing --- public/src/modules/api.js | 34 ++++++++++++++++++++-------------- 1 file changed, 20 insertions(+), 14 deletions(-) diff --git a/public/src/modules/api.js b/public/src/modules/api.js index 8c9485e557..0993a8de66 100644 --- a/public/src/modules/api.js +++ b/public/src/modules/api.js @@ -63,20 +63,26 @@ async function xhr(options, cb) { delete options.data; } - await fetch(url, { - ...options, - }).then(async (res) => { - const response = await res.json(); - if (Math.floor(res.status / 100) === 2) { - cb(null, ( - response && - response.hasOwnProperty('status') && - response.hasOwnProperty('response') ? response.response : (response || {}) - )); - } else { - cb(new Error(response.status.message)); - } - }).catch(cb); + const res = await fetch(url, options); + const { headers } = res; + const isJSON = headers.get('content-type').startsWith('application/json'); + + let response; + if (isJSON) { + response = await res.json(); + } else { + response = await res.text(); + } + + if (!res.ok) { + return cb(new Error(isJSON ? response.status.message : response)); + } + + cb(null, ( + isJSON && response.hasOwnProperty('status') && response.hasOwnProperty('response') ? + response.response : + response + )); } export function get(route, data, onSuccess) {