-
Notifications
You must be signed in to change notification settings - Fork 0
/
fetchAPI.ActionHandler.class.min.js
1 lines (1 loc) · 2.14 KB
/
fetchAPI.ActionHandler.class.min.js
1
class ActionHandler{constructor(e={}){if(this.options=Object.assign({eventType:"click",selector:".adminPanel__perform-action",confirmMessages:{approve:"Are you sure you want to give this person access to an account?",reject:"Are you sure this person does not require an account?"},uris:{approve:null,reject:null},defaultUri:"path/to/file.php",toastOptions:{borderColour:"darkgreen",textColour:"darkgreen"},body:()=>new FormData},e),this.errMsgList=[],!this.options.uris.approve&&!this.options.uris.reject&&!this.options.defaultUri)throw new Error("At least one URI must be provided.");this.initialize()}initialize(){document.querySelectorAll(this.options.selector).forEach((e=>{e.addEventListener(this.options.eventType,(t=>{const o=e.dataset.action||this.options.defaultUri;this.actionRequest(e,o)}))}))}async actionRequest(e,t){const o=this.options.uris.approve,s=this.options.uris.reject;let r=o||s||this.options.defaultUri;const i=this.options.confirmMessages[t]||this.options.confirmMessages.reject;if(!confirm(i))return;this.clearErrors();const n=this.options.body();try{const o=await fetch(r,{method:"POST",mode:"cors",credentials:"include",headers:{"Content-Type":this.options.body()instanceof FormData?"multipart/form-data":"application/x-www-form-urlencoded"},body:n}),s=await o.json();if("ok"===s.status){const e="approve"===t?"User Approved!":"Request Deleted!";this.toastMessage(`<i class="fa-solid fa-circle-check" style="color:darkgreen;"></i> ${e}`,this.options.toastOptions)}else this.handleErrors(s.errors,e)}catch(e){console.error(e)}}handleErrors(e,t){let o,s=1;t.style.borderColor="#c03",this.toastMessage('<i class="fa-solid fa-circle-x" style="color:#c03;"></i> Something went wrong!'),e.forEach((e=>{const t=e.src,r=e.msg,i=document.querySelector(`#${t}`);i.style.borderColor="#c03",i.classList.add("inputErrorIcon"),i.insertAdjacentHTML("afterend",`<p id="showError${t}" class="errorText fontSize12">${r}</p>`),this.errMsgList.push(document.querySelector(`#showError${t}`)),1===s&&(o=i),s++})),o&&o.scrollIntoView({behavior:"smooth"})}clearErrors(){this.errMsgList.forEach((e=>e.remove())),this.errMsgList=[]}toastMessage(e,t={}){console.log("Toast Message: ",e)}}