Add error returned from the request

This commit is contained in:
2025-01-14 12:51:29 +01:00
parent 2847c53bca
commit c878b33649

View File

@ -65,6 +65,15 @@
</div>
</form>
<div x-show="errorMessage || Object.keys(errorDetails).length > 0" class="error-container">
<h2 x-text="errorMessage"></h2>
<ul>
<template x-for="(message, field) in errorDetails" :key="field">
<li><strong x-text="field"></strong>: <span x-text="message"></span></li>
</template>
</ul>
</div>
<template x-if="createdElectionId > 0">
<div class="election-info">
<h2>Election Created Successfully</h2>
@ -103,8 +112,8 @@
</div>
<script>
document.addEventListener('alpine:init', () => {
Alpine.data('electionForm', () => ({
document.addEventListener("alpine:init", () => {
Alpine.data("electionForm", () => ({
election: {
name: "",
tokens: 100,
@ -115,6 +124,8 @@
},
createdElectionId: 0,
voterIdentities: [],
errorMessage: "",
errorDetails: {},
addChoice() {
this.election.choices.push(""); // Add a new empty choice
@ -128,46 +139,55 @@
try {
await navigator.clipboard.writeText(code);
} catch (err) {
console.error('Failed to copy code:', err);
console.error("Failed to copy code:", err);
}
},
async copyAllCodes() {
try {
const allCodes = this.voterIdentities.join('\n');
const allCodes = this.voterIdentities.join("\n");
await navigator.clipboard.writeText(allCodes);
} catch (err) {
console.error('Failed to copy codes:', err);
console.error("Failed to copy codes:", err);
}
},
createElection() {
async createElection() {
this.errorMessage = "";
this.errorDetails = {};
this.voterIdentities = [];
const payload = {
...this.election,
expiresAt: this.election.expiresAt + ":00Z", // Add timezone if necessary
choices: this.election.choices.filter(choice => choice.trim() !== "") // Filter out empty choices
expiresAt: this.election.expiresAt + ":00Z",
choices: this.election.choices.filter(choice => choice.trim() !== "")
};
fetch("/api/election", {
try {
const response = await fetch("/api/election", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(payload)
})
.then(response => {
const locationHeader = response.headers.get('Location');
this.createdElectionId = locationHeader.replace('/election/', '');
return response.json();
})
.then(data => {
this.voterIdentities = data.voterIdentities;
})
.catch(error => {
alert("Failed to create election.");
});
if (!response.ok) {
const errorData = await response.json();
this.errorMessage = errorData.message || "An error occurred.";
this.errorDetails = errorData.details?.fields || {};
return;
}
const locationHeader = response.headers.get("Location");
this.createdElectionId = locationHeader.replace("/election/", "");
const data = await response.json();
this.voterIdentities = data.voterIdentities;
} catch (error) {
this.errorMessage = "Failed to create election.";
console.error(error);
}
}
}));
});