Files
parts_website/static/js/api.js

60 lines
1.7 KiB
JavaScript

import DOM from './dom.js';
export default class API {
static getCsrfToken() {
return document.querySelector(idCSRFToken).getAttribute('content');
}
static async request(hashEndpoint, method = 'GET', data = null, params = null) {
const url = API.getUrlFromHash(hashEndpoint, params);
const csrfToken = API.getCsrfToken();
const options = {
method,
headers: {
'Content-Type': 'application/json',
[flagCsrfToken]: csrfToken,
}
};
if (data && (method === 'POST' || method === 'PUT' || method === 'PATCH')) {
data = {
...data,
[flagCsrfToken]: csrfToken,
};
options.body = JSON.stringify(data);
}
try {
const response = await fetch(url, options);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return await response.json();
} catch (error) {
console.error('API request failed:', error);
throw error;
}
}
static getUrlFromHash(hash, params = null) {
if (hash == null) hash = hashPageHome;
let url = API.parameteriseUrl(_pathHost + hash, params);
return url;
}
static parameteriseUrl(url, params) {
if (params) {
url += '?' + new URLSearchParams(params).toString();
}
return url;
}
static goToUrl(url) {
window.location.href = url;
}
static goToHash(hash, params = null) {
const url = API.getUrlFromHash(hash, params);
API.goToUrl(url);
}
}