Newer
Older
user_id: number;
firstName: string;
lastName: string;
eMail: string;
adress: string;
role: string;
}
let modalEl: bootstrap.Modal
document.addEventListener("DOMContentLoaded", (): void => {
modalEl = new bootstrap.Modal("#edit-user-modal");
//--- check, if user is already logged in (e.g. after refresh) -------------------------------------------------------
checkLogin();
//--- Form Eventhandlers -------------------------------------------------------
document.getElementById("add-user-form")!.addEventListener("submit", async (event: SubmitEvent): Promise<void> => {
event.preventDefault();
const emailEl: HTMLInputElement = document.getElementById("add-user-email") as HTMLInputElement;
const passwordEl: HTMLInputElement = document.getElementById("add-user-password") as HTMLInputElement;
const firstNameEl: HTMLInputElement = document.getElementById("add-user-first-name") as HTMLInputElement;
const lastNameEl: HTMLInputElement = document.getElementById("add-user-last-name") as HTMLInputElement;
const email: string = emailEl.value;
const firstName: string = firstNameEl.value;
const lastName: string = lastNameEl.value;
// Check, if any given value is empty.
// Don't allow creation of users without given name or family name.
if (firstName.length == 0 || lastName.length == 0 || email.length == 0 || password.length == 0) {
addMessage("The given name or family name is empty.");
return;
}
// Send user data via http to server using the route /user
const res: Response = await fetch('/user', {
method: 'post',
headers: {
"Content-type": "application/json"
},
});
const data: any = await res.json();
addMessage(data.message);
// Update the html
readUsers();
// Clear the input fields
});
document.getElementById("edit-user-form")!.addEventListener("submit", async (event: SubmitEvent): Promise<void> => {
event.preventDefault();
let idEl: HTMLInputElement = document.getElementById("edit-user-id") as HTMLInputElement;
let firstNameEl: HTMLInputElement = document.getElementById("edit-user-first-name") as HTMLInputElement;
let lastNameEl: HTMLInputElement = document.getElementById("edit-user-last-name") as HTMLInputElement;
// Read the user's id from the hidden field.
let userId: number = parseInt(idEl.value);
let firstName: string = firstNameEl.value;
let lastName: string = lastNameEl.value;
const res: Response = await fetch('/user/' + userId, {
method: 'put',
headers: {
"Content-type": "application/json"
},
});
const data: any = await res.json();
addMessage(data.message);
// Hide the modal window
modalEl.hide();
// Update the html
readUsers();
});
document.getElementById("login-form")!.addEventListener("submit", async (event: SubmitEvent): Promise<void> => {
event.preventDefault();
const emailInput: HTMLInputElement = document.getElementById('login-user-email-input') as HTMLInputElement;
const passwordInput: HTMLInputElement = document.getElementById('login-user-password-input') as HTMLInputElement;
const password: string = passwordInput.value;
const response: Response = await fetch('http://localhost:8080/login', {
method: "POST",
headers: {
"Content-type": "application/json"
},
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
}
);
if (response.status === 400 || response.status === 401) {
const data: any = await response.json();
addMessage(data.message);
} else if (response.status === 200) {
const data: any = await response.json();
addMessage(data.message);
showLoggedInStatus(data.user);
} else {
console.warn(`Unhandled response code (${response.status}).`)
}
});
document.getElementById("logout-form")!.addEventListener("submit", async (event: SubmitEvent): Promise<void> => {
event.preventDefault();
await fetch('http://localhost:8080/logout', {
method: "POST",
}
);
showLoggedOutStatus()
});
});
/**
* Checks if user might be logged
*/
async function checkLogin(): Promise<void> {
const response: Response = await fetch('/login', {
method: "GET"
}
);
if (response.status === 200) {
const data: any = await response.json();
showLoggedInStatus(data.user);
}
}
/**
* Gets and displays all users
*/
async function readUsers(): Promise<void> {
const res: Response = await fetch('/users', {
method: "GET"
}
);
const data: any = await res.json();
renderList(data.userList);
}
/**
* Displays the logged in username
*/
function showLoggedInStatus(user: User): void {
const email: HTMLElement = document.getElementById('current-user-email')!;
email.innerHTML = `Hello ${user.firstName}`;
const addUserForm: HTMLElement = document.getElementById('add-user-container')!;
addUserForm.classList.remove("d-none"); // show content area
const contentArea: HTMLElement = document.getElementById('user-list-container')!;
contentArea.classList.remove("d-none"); // show content area
const login: HTMLElement = document.getElementById('login-container')!;
login.classList.add("d-none"); // hide login
const logout: HTMLElement = document.getElementById('logout-container')!;
logout.classList.remove("d-none"); // show logout
(document.getElementById('login-form') as HTMLFormElement).reset();
readUsers();
}
/**
* Resets the site to the logged-out state.
* Clears user list, shows login form, hides logout form-
*/
function showLoggedOutStatus(): void {
const email: HTMLElement = document.getElementById('current-user-email')!;
email.innerHTML = ``;
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
const addUserForm: HTMLElement = document.getElementById('add-user-container')!;
addUserForm.classList.add("d-none"); // hide content area
const contentArea: HTMLElement = document.getElementById('user-list-container')!;
contentArea.classList.add("d-none"); // hide content area
const login: HTMLElement = document.getElementById('login-container')!;
login.classList.remove("d-none"); // show login
const logout: HTMLElement = document.getElementById('logout-container')!;
logout.classList.add("d-none"); // hide logout
(document.getElementById('add-user-form') as HTMLFormElement).reset();
}
/**
* 1) Clears the user table.
* 2) Adds all users to the table.
*/
function renderList(userList: User[]): void {
let userListEl: HTMLElement = document.getElementById("user-list")!;
// Remove all entries from the table
userListEl.replaceChildren();
for (let user of userList) {
// The new table row
let tr: HTMLTableRowElement = document.createElement("tr");
// ID cell
let tdUser_id: HTMLTableCellElement = document.createElement("td");
tdUser_id.textContent = user.user_id.toString();
let tdFirstName: HTMLTableCellElement = document.createElement("td");
tdFirstName.textContent = user.firstName;
let tdLastName: HTMLTableCellElement = document.createElement("td");
tdLastName.textContent = user.lastName;
// email cell
let tdEmail: HTMLTableCellElement = document.createElement("td");
tdEmail.textContent = user.eMail;
// adress cell
let tdAdress: HTMLTableCellElement = document.createElement("td");
tdAdress.textContent = user.adress;
// role cell
let tdRole: HTMLTableCellElement = document.createElement("td");
tdRole.textContent = user.role;
// Buttons cell
let tdButtons: HTMLTableCellElement = document.createElement("td");
// Delete button
let deleteButton: HTMLButtonElement = document.createElement("button");
deleteButton.className = "btn btn-danger";
deleteButton.addEventListener("click", async () => {
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
method: 'DELETE'
});
const data: any = await res.json();
addMessage(data.message);
readUsers();
});
// Delete button icon
let deleteButtonIcon: HTMLElement = document.createElement("i");
deleteButtonIcon.className = "fa-solid fa-trash";
deleteButton.append(deleteButtonIcon);
// Edit button
let editButton: HTMLButtonElement = document.createElement("button");
editButton.className = "btn btn-primary ms-3";
editButton.addEventListener("click", () => {
showEditModal(user);
});
// Edit button icon
let editButtonIcon: HTMLElement = document.createElement("i");
editButtonIcon.className = "fa-solid fa-pen";
editButton.append(editButtonIcon);
// Adds the buttons to the button cell
tdButtons.append(deleteButton, editButton);
// Add the cells to the table row
tr.append(tdUser_id, tdFirstName, tdLastName, tdEmail,tdAdress, tdRole, tdButtons);
// Add the table row to the table
userListEl.append(tr);
}
}
/**
* 1) Fills the modal window with the given user's data.
* 2) Opens the modal window.
*/
function showEditModal(user: User): void {
let user_idEl: HTMLInputElement = document.getElementById("edit-user-user_id") as HTMLInputElement;
let firstNameEl: HTMLInputElement = document.getElementById("edit-user-first-name") as HTMLInputElement;
let lastNameEl: HTMLInputElement = document.getElementById("edit-user-last-name") as HTMLInputElement;
firstNameEl.value = user.firstName;
lastNameEl.value = user.lastName;
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
// Show the modal window.
modalEl.show();
}
/**
* Creates a new alert message.
*/
function addMessage(message: string): void {
const messagesEl: HTMLElement = document.getElementById('messages')!;
// The alert element
let alertEl: HTMLElement = document.createElement('div');
alertEl.classList.add('alert', 'alert-warning', 'alert-dismissible', 'fade', 'show');
alertEl.setAttribute('role', 'alert');
alertEl.textContent = message;
// Close button
let buttonEl: HTMLElement = document.createElement("button");
// btn-close changes the button into an 'X' icon.
buttonEl.className = "btn-close";
// data-bs-dismiss enables the button to automatically close the alert on click.
buttonEl.setAttribute("data-bs-dismiss", "alert");
// Add the close button to the alert.
alertEl.appendChild(buttonEl);
// Convert to Bootstrap Alert type
const alert: bootstrap.Alert = new bootstrap.Alert(alertEl);
// Add message to DOM
messagesEl.appendChild(alertEl);
// Auto-remove message after 5 seconds (5000ms)
setTimeout(() => {
alert.close();
}, 5000);
}