philomena/assets/js/utils/requests.js

91 lines
1.9 KiB
JavaScript
Raw Normal View History

2019-10-05 02:09:52 +02:00
/**
* Request Utils
*/
2021-10-28 05:36:13 +02:00
import { wait } from './async';
2019-10-05 02:09:52 +02:00
function fetchJson(verb, endpoint, body) {
const data = {
method: verb,
credentials: 'same-origin',
headers: {
'Content-Type': 'application/json',
2020-09-28 05:53:14 +02:00
'x-csrf-token': window.booru.csrfToken,
'x-requested-with': 'xmlhttprequest'
2019-10-05 02:09:52 +02:00
},
};
if (body) {
body._method = verb;
data.body = JSON.stringify(body);
}
return fetch(endpoint, data);
}
function fetchHtml(endpoint) {
return fetch(endpoint, {
credentials: 'same-origin',
headers: {
2020-09-28 05:53:14 +02:00
'x-csrf-token': window.booru.csrfToken,
'x-requested-with': 'xmlhttprequest'
2019-10-05 02:09:52 +02:00
},
});
}
function handleError(response) {
if (!response.ok) {
throw new Error('Received error from server');
}
return response;
}
2021-10-26 05:42:29 +02:00
/** @returns {Promise<Response>} */
function fetchBackoff(...fetchArgs) {
/**
* @param timeout {number}
* @returns {Promise<Response>}
*/
function fetchBackoffTimeout(timeout) {
// Adjust timeout
const newTimeout = Math.min(timeout * 2, 300000);
// Try to fetch the thing
return fetch(...fetchArgs)
.then(handleError)
.catch(() =>
2021-10-28 05:36:13 +02:00
wait(timeout).then(fetchBackoffTimeout(newTimeout))
2021-10-26 05:42:29 +02:00
);
}
return fetchBackoffTimeout(5000);
}
2021-10-28 05:36:13 +02:00
/**
* Escape a filename for inclusion in a Content-Disposition
* response header.
*
* @param {string} name
* @returns {string}
*/
function escapeFilename(name) {
return name
.replace(/[^-_+a-zA-Z0-9]/, '_')
.substring(0, 150);
}
/**
* Run the wrapped function if the response was okay,
* otherwise return the response.
* @param {(_: Response) => Response} responseGenerator
* @returns {(_: Response) => Response}
*/
function ifOk(responseGenerator) {
return resp => {
if (resp.ok) return new Response(responseGenerator(resp));
return resp;
};
}
export { fetchJson, fetchHtml, fetchBackoff, handleError, escapeFilename, ifOk };