switch makeCaptureRequest to fetch api in preparation for manifest v3

This commit is contained in:
Dima Gerasimov 2022-12-24 03:28:54 +00:00 committed by karlicoss
parent 20022db1f6
commit 5bdd5116e7

View file

@ -15,65 +15,50 @@ type Params = {
} }
function makeCaptureRequest( async function makeCaptureRequest(
params: Params, params: Params,
options: Options, options: Options,
) { ) {
if (params.tag_str == null) { if (params.tag_str == null) {
params.tag_str = options.default_tags; params.tag_str = options.default_tags
} }
const data = JSON.stringify(params); const endpoint = options.endpoint
console.log(`[background] capturing ${data}`);
var request = new XMLHttpRequest(); const data = JSON.stringify(params)
const curl = options.endpoint; console.log(`capturing ${data} via ${endpoint}`)
request.timeout = 10 * 1000; // TODO should it be configurable?
request.open('POST', curl, true); // TODO maybe handle catch first and then again?
request.onreadystatechange = () => {
const XHR_DONE = 4; await fetch(endpoint, {
if (request.readyState != XHR_DONE) { method: 'POST',
return; headers: {
'Content-Type': 'application/json',
},
body: data,
}).catch((err: Error) => {
// fetch only rejects when host is unavailable
console.error(err)
throw new Error(`${endpoint} unavailable, check if server is running`)
}).then(async response => {
if (!response.ok) { // http error
throw new Error(`${endpoint}: HTTP ${response.status} ${response.statusText}`)
} }
const status = request.status; const jres = await response.json()
const rtext = request.responseText; const path = jres.path
var had_error = false; console.log(`success: ${jres}`);
var error_message = `status ${status}, response ${rtext}`;
console.log(`[background] status: ${status}, response: ${rtext}`);
if (status >= 200 && status < 400) { // success
try {
// TODO handle json parsing defensively here
const response = JSON.parse(rtext);
const path = response.path;
console.log(`[background] success: ${rtext}`);
if (options.notification) { if (options.notification) {
showNotification(`OK: captured to ${path}`); showNotification(`OK: captured to ${path}`);
} }
} catch (err) { }).catch((err: Error) => {
had_error = true; console.error(err)
error_message = error_message.concat(String(err)); // todo make sure we catch errors from then clause too?
console.error(err); const error_message = `ERROR: ${err.toString()}`
} console.error(error_message);
} else { showNotification(error_message, 1);
had_error = true;
if (status == 0) {
error_message = error_message.concat(` ${curl} must be unavailable `);
}
}
if (had_error) {
console.error(`[background] ERROR: ${error_message}`);
showNotification(`ERROR: ${error_message}`, 1);
// TODO crap, doesn't really seem to respect urgency... // TODO crap, doesn't really seem to respect urgency...
} })
};
request.onerror = () => {
console.error(request);
};
request.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
request.send(data);
} }