Files
ad/molodetz/static/js/utils/Http.js
T

73 lines
2.3 KiB
JavaScript

// retoor <retoor@molodetz.nl>
export class Http {
static termsGate = null;
static suspend() {
return new Promise(() => {});
}
static async getJson(url) {
const response = await fetch(url, { headers: { Accept: "application/json" }, credentials: "same-origin" });
if (!response.ok) {
throw new Error(`${response.status} ${response.statusText}`);
}
return response.json();
}
static async #post(url, body, headers) {
const response = await fetch(url, {
method: "POST",
body,
credentials: "same-origin",
headers: { Accept: "application/json", ...headers },
});
if (response.status === 403 && Http.termsGate) {
const handled = await Http.termsGate.intercept(response.clone());
if (handled) {
return Http.#post(url, body, headers);
}
}
if (response.redirected && response.url.includes("/auth/login")) {
window.location.href = response.url;
return Http.suspend();
}
return response;
}
static async send(url, data = {}) {
const response = await Http.#post(url, JSON.stringify(data), { "Content-Type": "application/json" });
const payload = await response.json().catch(() => ({}));
if (!response.ok || payload.ok === false) {
const message = payload.error?.message || (payload.messages || []).join(", ") || response.statusText;
throw new Error(message);
}
return payload;
}
static async sendForm(url, form) {
const body = new URLSearchParams(new FormData(form));
const response = await Http.#post(url, body, { "Content-Type": "application/x-www-form-urlencoded" });
if (!response.ok) {
const payload = await response.json().catch(() => ({}));
throw new Error(`${response.status} ${payload.error?.message || (payload.messages || []).join(", ") || ""}`.trim());
}
return response.json().catch(() => ({ ok: true }));
}
static postJson(url, data) {
return Http.send(url, data);
}
static postForm(url, form) {
return Http.sendForm(url, form);
}
static async sendDelete(url) {
const response = await fetch(url, { method: "DELETE", credentials: "same-origin", headers: { Accept: "application/json" } });
if (!response.ok) {
throw new Error(`${response.status}`);
}
return response.json().catch(() => ({ ok: true }));
}
}