fix data setting get datatable using api token

This commit is contained in:
arifal
2025-06-17 11:54:02 +07:00
parent a8b02afad9
commit 285ff46c2b
10 changed files with 586 additions and 56 deletions

View File

@@ -10,16 +10,81 @@ class DataSettings {
this.toastElement = document.getElementById("toastNotification");
this.toast = new bootstrap.Toast(this.toastElement);
this.table = null;
// Initialize immediately
this.init();
}
// Initialize functions
/**
* Initialize the DataSettings class
*/
init() {
this.initTableDataSettings();
this.initEvents();
}
/**
* Get API token from meta tag
* @returns {string|null}
*/
getApiToken() {
const tokenMeta = document.querySelector('meta[name="api-token"]');
return tokenMeta ? tokenMeta.getAttribute('content') : null;
}
/**
* Get authentication headers for API requests
* @returns {object}
*/
getAuthHeaders() {
const token = this.getApiToken();
const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content');
const headers = {
'Content-Type': 'application/json',
'Accept': 'application/json',
};
if (token) {
headers['Authorization'] = `Bearer ${token}`;
}
if (csrfToken) {
headers['X-CSRF-TOKEN'] = csrfToken;
}
return headers;
}
/**
* Make API request with authentication
* @param {string} url
* @param {object} options
* @returns {Promise}
*/
async makeApiRequest(url, options = {}) {
const defaultOptions = {
headers: this.getAuthHeaders(),
...options
};
try {
const response = await fetch(url, defaultOptions);
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
return response;
} catch (error) {
console.error('API Request failed:', error);
throw error;
}
}
initEvents() {
document.body.addEventListener("click", async (event) => {
const deleteButton = event.target.closest(
".btn-delete-data-settings"
);
const deleteButton = event.target.closest(".btn-delete-data-settings");
if (deleteButton) {
event.preventDefault();
await this.handleDelete(deleteButton);
@@ -34,7 +99,8 @@ class DataSettings {
let canUpdate = tableContainer.getAttribute("data-updater") === "1";
let canDelete = tableContainer.getAttribute("data-destroyer") === "1";
let menuId = tableContainer.getAttribute("data-menuId");
// Create a new Grid.js instance only if it doesn't exist
// Create a new Grid.js instance
this.table = new Grid({
columns: [
"ID",
@@ -77,9 +143,7 @@ class DataSettings {
limit: 15,
server: {
url: (prev, page) =>
`${prev}${prev.includes("?") ? "&" : "?"}page=${
page + 1
}`,
`${prev}${prev.includes("?") ? "&" : "?"}page=${page + 1}`,
},
},
sort: true,
@@ -91,13 +155,7 @@ class DataSettings {
},
server: {
url: `${GlobalConfig.apiHost}/api/data-settings`,
headers: {
"X-CSRF-TOKEN": document
.querySelector('meta[name="csrf-token"]')
.getAttribute("content"),
"Content-Type": "application/json",
"Accept": "application/json",
},
headers: this.getAuthHeaders(),
then: (data) =>
data.data.map((item) => [
item.id,
@@ -110,6 +168,7 @@ class DataSettings {
},
}).render(tableContainer);
}
async handleDelete(deleteButton) {
const id = deleteButton.getAttribute("data-id");
@@ -125,46 +184,29 @@ class DataSettings {
if (result.isConfirmed) {
try {
let response = await fetch(
const response = await this.makeApiRequest(
`${GlobalConfig.apiHost}/api/data-settings/${id}`,
{
method: "DELETE",
credentials: "include",
headers: {
"X-CSRF-TOKEN": document
.querySelector('meta[name="csrf-token"]')
.getAttribute("content"),
"Content-Type": "application/json",
"Accept": "application/json",
},
}
{ method: "DELETE" }
);
if (response.ok) {
let result = await response.json();
this.toastMessage.innerText =
result.message || "Deleted successfully!";
this.toast.show();
const result = await response.json();
this.toastMessage.innerText = result.message || "Deleted successfully!";
this.toast.show();
// Refresh Grid.js table
if (typeof this.table !== "undefined") {
this.table.updateConfig({}).forceRender();
}
} else {
let error = await response.json();
console.error("Delete failed:", error);
this.toastMessage.innerText =
error.message || "Delete failed!";
this.toast.show();
// Refresh Grid.js table
if (this.table) {
this.table.updateConfig({}).forceRender();
}
} catch (error) {
console.error("Error deleting item:", error);
this.toastMessage.innerText = "An error occurred!";
this.toastMessage.innerText = error.message || "An error occurred!";
this.toast.show();
}
}
}
}
document.addEventListener("DOMContentLoaded", function (e) {
// Initialize when DOM is ready
document.addEventListener("DOMContentLoaded", function () {
new DataSettings();
});