Created
October 4, 2024 02:17
-
-
Save NobodyButMe-Haiya/513905010b8d3afd3c3a802371f78247 to your computer and use it in GitHub Desktop.
JS class
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class TenantClass { | |
/** | |
* Creates an instance of Tenant Class | |
* | |
* @constructor | |
* @param {string} key - The primary key for the record. | |
* @param {AbortSignal} signal - The signal for aborting the fetch request. | |
*/ | |
constructor(key, signal) { | |
this.key = key; | |
this.signal = signal; | |
this._uri = API.version + "/tenant/"; | |
this._colspan = 3; | |
} | |
/** | |
* Generate Request Body for fetch API | |
* @param {TenantRecord?} tenant | |
* @param {string?} search | |
* @returns | |
*/ | |
requestBody = (tenant, search) => { | |
const body = {} | |
if (tenant) { | |
body.name = API.encodeHTML(tenant.getName()) | |
if (tenant.getKey() !== null && tenant.getKey() !== undefined) { | |
body.Key = tenant.getKey(); | |
} | |
} else if (search) { | |
body.Search = search; | |
} | |
return JSON.stringify(body); | |
} | |
/** | |
* Template for Tenant | |
* @param {TenantRecord} record | |
* @param {ViewRecord} view | |
* @returns {HTMLTableRowElement} The generated <tr> element representing the table row for the user. | |
*/ | |
renderRow = (record, view) => { | |
const row = new TableRowHelper(`row-${record.getKey()}`); | |
return row | |
.addTextInput(`name-${record.getKey()}`, record.getName(), 64, /^[a-zA-Z0-9\s]*$/) | |
.addActionButtons(view, record.getKey()) | |
.getRow(); // Return the constructed <tr> element | |
} | |
/*** | |
* Get Form Field | |
* @param {string?} key | |
*/ | |
getFormField = (key) => { | |
let token = document.querySelector('input[name="__RequestVerificationToken"]') | |
if (key === null || key === undefined) { | |
return { | |
name: document.getElementById("name"), | |
tableBody: document.getElementById("tableBody"), | |
search: document.getElementById("search"), | |
token: token | |
}; | |
} else { | |
return { | |
row: document.getElementById("row-" + key), | |
name: document.getElementById("name-" + key), | |
token: token | |
}; | |
} | |
} | |
/** | |
* Add new row | |
* @param {TenantRecord} record | |
* @param {ViewRecord} view | |
* @returns | |
*/ | |
addRow = (record, view) => { | |
let row = this.renderRow(record, view); | |
let fragment = document.createDocumentFragment(); | |
fragment.appendChild(row); | |
const {tableBody} = this.getFormField(); | |
if (tableBody.firstChild) { | |
tableBody.insertBefore(fragment, tableBody.firstChild); | |
} else { | |
tableBody.appendChild(fragment); // If there's no existing row, just append it | |
} | |
} | |
createRecord = async () => { | |
const { | |
name, | |
token | |
} = this.getFormField(); | |
let nameClassList = name.classList; | |
if (name.value.length === 0) { | |
API.errorEmptyField(); | |
nameClassList.add("is-invalid"); | |
name.focus(); | |
} else { | |
nameClassList.remove("is-invalid"); | |
const record = new TenantRecord() | |
.setName(name.value); | |
const requestBody = this.requestBody(record); | |
const init = API.init(this.signal, this.key, requestBody, token.value); | |
try { | |
let response = await API.fetchApi(API.getUrl(this._uri, Method.CREATE), init); | |
if (response.success) { | |
record.setKey(response.key); | |
let view = response.view; | |
let viewRecord = new ViewRecord().setCreate(view.create).setRead(view.read).setUpdate(view.update).setDelete(view.delete) | |
this.addRow(record,viewRecord ); | |
API.createSuccess(); | |
name.value = ""; | |
} else { | |
API.failureCreateMessage(); | |
} | |
name.value = ''; | |
} catch (error) { | |
console.log(error); | |
API.failureMessage(); | |
} | |
} | |
} | |
readRecord = async () => { | |
const {tableBody, search, token} = this.getFormField(); | |
search.value = ""; | |
const requestBody = this.requestBody(); | |
const init = API.init(this.signal, this.key, requestBody, token.value); | |
try { | |
let response = await API.fetchApi(API.getUrl(this._uri, Method.READ), init); | |
if (response.data === undefined || response.data.length === 0) { | |
tableBody.innerHTML = ""; | |
tableBody.append(API.emptyCell(this._colspan)); | |
} else { | |
tableBody.innerHTML = ""; | |
tableBody.append((response.data.length === 0) ? | |
API.emptyCell(this._colspan) | |
: this.createRowsFromData(response.data,response.view)); | |
} | |
} catch (error) { | |
API.failureMessage(); | |
} | |
} | |
searchRecord = async () => { | |
const {tableBody, search, token} = this.getFormField(); | |
if (search.value === '') { | |
API.searchEmpty(); | |
return; | |
} | |
if (search.value.length < API.minLengthSearch) { | |
API.lessThanThree(); | |
return; | |
} | |
const requestBody = this.requestBody(null, search.value); | |
const init = API.init(this.signal, this.key, requestBody, token.value); | |
try { | |
let response = await API.fetchApi(API.getUrl(this._uri, Method.SEARCH), init); | |
if (response.data === undefined || response.data.length === 0) { | |
tableBody.innerHTML = ""; | |
tableBody.append(API.emptyCell(this._colspan)); | |
} else { | |
tableBody.innerHTML = ""; | |
tableBody.append((response.data.length === 0) ? | |
API.emptyCell(this._colspan) | |
: this.createRowsFromData(response.data, response.view)); | |
} | |
} catch (error) { | |
console.log(error); | |
API.failureMessage(); | |
} | |
} | |
/** | |
* Creates a document fragment with rows based on provided data and view settings. | |
* | |
* @param {Array<Object>} data - An array of objects | |
* @param {Object} view - An object containing view permissions (create, read, update, delete). | |
* @param {boolean} view.create - Permission to create. | |
* @param {boolean} view.read - Permission to read. | |
* @param {boolean} view.update - Permission to update. | |
* @param {boolean} view.delete - Permission to delete. | |
* @returns {DocumentFragment} - A document fragment containing the created rows. | |
*/ | |
createRowsFromData = (data, view) => { | |
let fragment = document.createDocumentFragment(); | |
data.forEach(({key, name}) => { | |
return fragment.appendChild(this.renderRow(new TenantRecord() | |
.setKey(key) | |
.setName(name), new ViewRecord() | |
.setCreate(view.create) | |
.setRead(view.read) | |
.setUpdate(view.update) | |
.setDelete(view.delete))); | |
}); | |
return fragment; | |
} | |
updateRecord = async (key) => { | |
const { | |
name, | |
token | |
} = this.getFormField(key); | |
let nameClassList = name.classList; | |
if (name.value.length === 0) { | |
API.errorEmptyField(); | |
nameClassList.add("is-invalid"); | |
name.focus(); | |
} else { | |
nameClassList.remove("is-invalid"); | |
const record = new TenantRecord() | |
.setKey(key) | |
.setName(name.value) | |
const requestBody = this.requestBody(record); | |
const init = API.init(this.signal, this.key, requestBody, token.value); | |
try { | |
await API.fetchApi(API.getUrl(this._uri, Method.UPDATE), init) ? | |
API.updateSuccess() : | |
API.failureUpdateMessage(); | |
} catch (error) { | |
API.failureMessage(); | |
} | |
} | |
} | |
deleteRecord = async (key) => { | |
try { | |
const result = await API.deleteMessage(); | |
result.isConfirmed ? | |
await this.deleteRecordProcess(key) : | |
API.deleteWarning(); | |
} catch (error) { | |
API.failureMessage(); | |
} | |
} | |
deleteRecordProcess = async (key) => { | |
const {row, token} = this.getFormField(key); | |
const record = new TenantRecord() | |
.setKey(key); | |
const requestBody = this.requestBody(record); | |
const init = API.init(this.signal, this.key, requestBody, token.value); | |
try { | |
if (await API.fetchApi(API.getUrl(this._uri, Method.DELETE), init)) { | |
row.remove(); | |
API.deleteSuccess(); | |
} else { | |
API.failureDeleteMessage(); | |
} | |
} catch (error) { | |
API.failureMessage(); | |
} | |
} | |
} | |
function TenantInit(key, signal) { | |
let obj = new TenantClass(key, signal); | |
const tenantListener = async (event) => { | |
const buttonClass = API.getButtonClass(event.target); | |
switch (buttonClass) { | |
case 'create-button': | |
await obj.createRecord(); | |
break; | |
case 'read-button': | |
await obj.readRecord(); | |
break; | |
case 'search-button': | |
await obj.searchRecord(); | |
break; | |
case 'delete-button': { | |
const key = event.target.closest('.delete-button').dataset.key; // Get key from the closest button | |
await obj.deleteRecord(key); | |
break; | |
} | |
case 'update-button': { | |
const key = event.target.closest('.update-button').dataset.key; // Get key from the closest button | |
await obj.updateRecord(key); | |
break; | |
} | |
} | |
}; | |
if (currentListener) { | |
document.removeEventListener("click", centralListener); | |
} | |
currentListener = tenantListener; | |
// Add the new centralized listener | |
document.addEventListener("click", centralListener); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment