feat: simplified api module handler logic, content-type detection/parsing

This commit is contained in:
Julian Lam
2023-07-11 11:03:00 -04:00
parent e72fab5417
commit 2d016af82f

View File

@@ -63,20 +63,26 @@ async function xhr(options, cb) {
delete options.data; delete options.data;
} }
await fetch(url, { const res = await fetch(url, options);
...options, const { headers } = res;
}).then(async (res) => { const isJSON = headers.get('content-type').startsWith('application/json');
const response = await res.json();
if (Math.floor(res.status / 100) === 2) { let response;
cb(null, ( if (isJSON) {
response && response = await res.json();
response.hasOwnProperty('status') &&
response.hasOwnProperty('response') ? response.response : (response || {})
));
} else { } else {
cb(new Error(response.status.message)); response = await res.text();
} }
}).catch(cb);
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) { export function get(route, data, onSuccess) {