Repository navigation
Expand file tree
/
Copy pathclasses.js
More file actions
363 lines (301 loc) · 12.4 KB
/
Copy pathclasses.js
File metadata and controls
363 lines (301 loc) · 12.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
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
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
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
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
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
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
console.log('classes.js is executing...');
const id_form_create_new_class = document.getElementById("id_form_create_new_class");
id_form_create_new_class.addEventListener('submit', handleCreateNewClassEvent);
const div_create_new_class = document.getElementById("create_new_class");
const div_show_class_details = document.getElementById("show_class_details");
const div_update_class_details = document.getElementById("update_class_details");
const div_delete_class = document.getElementById("delete_class");
const div_list_of_classes = document.getElementById("list_of_classes");
// // TODO: uncomment the following code to fetch and display the classes after the page loads
// document.addEventListener("DOMContentLoaded", async function()
// {
// await getAndDisplayAllClasses();
// });
// =====================================================================================================================
// Functions that interact with the API
// =====================================================================================================================
async function createNewClass(classData)
{
const API_URL = 'http://localhost:8080/classes';
try
{
const response = await fetch(API_URL, {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded"
},
body: new URLSearchParams(classData)
});
console.log({response});
console.log(`response.status = ${response.status}`);
console.log(`response.statusText = ${response.statusText}`);
console.log(`response.ok = ${response.ok}`);
if (response.ok)
{
const createdClass = await response.json();
div_create_new_class.innerHTML = `<p class="success">Class created successfully. The new class id is ${createdClass.id}</p>`;
await getAndDisplayAllClasses();
}
else
{
div_create_new_class.innerHTML = '<p class="failure">ERROR: failed to create the new class</p>';
}
}
catch (error)
{
console.error(error);
div_create_new_class.innerHTML = `<p class="failure">ERROR: failed to connect to the API to create the new class</p>`;
}
}
async function getAndDisplayAllClasses()
{
console.log('getAndDisplayAllClasses - START');
const API_URL = "http://localhost:8080/classes";
div_list_of_classes.innerHTML = "Calling the API to get the list of classes...";
try
{
const response = await fetch(API_URL);
console.log({response});
console.log(`response.status = ${response.status}`);
console.log(`response.statusText = ${response.statusText}`);
console.log(`response.ok = ${response.ok}`);
if (response.ok)
{
div_list_of_classes.innerHTML = "Retrieved the classes successfully, now we just need to process them...";
const listOfClassesAsJSON = await response.json();
console.log({listOfClasses: listOfClassesAsJSON});
displayClasses(listOfClassesAsJSON);
}
else
{
div_list_of_classes.innerHTML = '<p class="failure">ERROR: failed to retrieve the classes.</p>';
}
}
catch (error)
{
console.error(error);
div_list_of_classes.innerHTML = '<p class="failure">ERROR: failed to connect to the API to fetch the classes data.</p>';
}
console.log('getAndDisplayAllClasses - END');
}
/**
* @return the class with id = classId as JSON or null if the class could not be retrieved from the API
*/
async function getClass(classId)
{
console.log(`getClass(${classId}) - START`);
console.log("classId = " + classId);
const API_URL = "http://localhost:8080/classes/" + classId;
console.log("Calling the API to get the class with id ${classId}...");
try
{
const response = await fetch(API_URL);
console.log({response});
console.log(`response.status = ${response.status}`);
console.log(`response.statusText = ${response.statusText}`);
console.log(`response.ok = ${response.ok}`);
if (response.ok)
{
console.log("Retrieved the class successfully, now we just need to process it...");
const classAsJSON = await response.json();
console.log({classAsJSON});
return classAsJSON;
}
else
{
console.log(`ERROR: failed to retrieve the class with id ${classId}`);
}
}
catch (error)
{
console.error(error);
console.log(`ERROR: failed to connect to the API to fetch the class with id ${classId}`);
}
console.log(`getClass(${classId}) - END`);
// if this code is reached, it means that an error occurred and the class could not be retrieved
return null;
}
async function updateClass(classData)
{
const API_URL = `http://localhost:8080/classes/${classData.id}`;
try
{
const response = await fetch(API_URL, {
method: "PATCH",
headers: {
"Content-Type": "application/x-www-form-urlencoded"
},
body: new URLSearchParams(classData)
});
console.log({response});
console.log(`response.status = ${response.status}`);
console.log(`response.statusText = ${response.statusText}`);
console.log(`response.ok = ${response.ok}`);
if (response.ok)
{
div_update_class_details.innerHTML = '<p class="success">Class updated successfully</p>';
await getAndDisplayAllClasses();
}
else
{
div_update_class_details.innerHTML = '<p class="failure">ERROR: failed to update the class</p>';
}
}
catch (error)
{
console.error(error);
div_update_class_details.innerHTML = `<p class="failure">ERROR: failed to update the class with id ${classData.id}</p>`;
}
}
async function deleteClass(classId)
{
const API_URL = `http://localhost:8080/classes/${classId}`;
try
{
const response = await fetch(API_URL, {method: "DELETE"});
console.log({response});
console.log(`response.status = ${response.status}`);
console.log(`response.statusText = ${response.statusText}`);
console.log(`response.ok = ${response.ok}`);
if (response.ok)
{
div_delete_class.innerHTML = `<p class="success">Class with id ${classId} deleted successfully</p>`;
await getAndDisplayAllClasses();
}
else
{
div_delete_class.innerHTML = `<p class="failure">ERROR: failed to delete the class with id ${classId}</p>`;
}
}
catch (error)
{
console.error(error);
div_delete_class.innerHTML = `<p class="failure">ERROR: failed to connect to the API to delete the class with id ${classId}</p>`;
}
}
// =====================================================================================================================
// Functions that update the HTML by manipulating the DOM
// =====================================================================================================================
async function handleCreateNewClassEvent(event)
{
// Prevent the default form submission behavior which will cause the page to be redirected to the action URL
event.preventDefault();
const formData = new FormData(id_form_create_new_class);
const classData =
{
code: formData.get("code"),
title: formData.get("title"),
description: formData.get("description"),
maxStudents: formData.get("maxStudents")
};
console.log({classData});
await createNewClass(classData);
}
function displayClasses(listOfClassesAsJSON)
{
div_list_of_classes.innerHTML = '';
for (const classAsJSON of listOfClassesAsJSON)
{
console.log({classAsJSON});
div_list_of_classes.innerHTML += renderClassAsHTML(classAsJSON);
}
}
function renderClassAsHTML(classAsJSON)
{
// data-class-id is a custom attribute that we use to store the id of the class, so that we can retrieve it later
// when the user clicks on the "Show Class Details" button, or the "Update Class Details" button, or the "Delete Class" button
return `<div class="show-class-in-list" data-class-id="${classAsJSON.id}">
<p>Class ID (this is just for debugging): ${classAsJSON.id}</p>
<p>Class code: ${classAsJSON.code}</p>
<p>Class title: ${classAsJSON.title}</p>
<p>Class description: ${classAsJSON.description}</p>
<p>Max students: ${classAsJSON.maxStudents}</p>
<p>
<!-- TODO: this is for extra credit -->
<a href="classes.show.html?class_id=${classAsJSON.id}">Show this class</a>
</p>
<button onclick="handleShowClassDetailsEvent(event)">Show Class Details</button>
<button onclick="handleUpdateClassDetailsEvent(event)">Update Class Details</button>
<button onclick="handleDeleteClassEvent(event)">Delete Class</button>
</div>`;
}
async function handleShowClassDetailsEvent(event)
{
console.log('handleShowClassDetailsEvent - START');
console.log(`event = ${event}`);
console.log({event});
const classId = event.target.parentElement.getAttribute("data-class-id");
let classAsJSON = await getClass(classId);
console.log({classAsJSON});
if (classAsJSON == null)
{
div_show_class_details.innerHTML = `<p class="failure">ERROR: failed to retrieve the class with id ${classId}</p>`;
}
else
{
displayClassDetails(classAsJSON);
}
console.log('handleShowClassDetailsEvent - END');
}
function displayClassDetails(classAsJSON)
{
console.log({classAsJSON});
div_show_class_details.innerHTML = `<div class="show-class-details" data-class-id="${classAsJSON.id}">
<p>Class ID (this is just for debugging): ${classAsJSON.id}</p>
<p><strong>${classAsJSON.code}: ${classAsJSON.title}</strong></p>
<p>Class description: ${classAsJSON.description}</p>
<p>Max students: ${classAsJSON.maxStudents}</p>
</div>`;
}
async function handleUpdateClassDetailsEvent(event)
{
console.log('handleUpdateClassDetailsEvent - START');
console.log(`event = ${event}`);
console.log({event});
const classId = event.target.parentElement.getAttribute("data-class-id");
const classAsJSON = await getClass(classId);
console.log({classAsJSON});
div_update_class_details.innerHTML =
`<form id="id_form_update_class_details">
<input type="hidden" name="id" value="${classAsJSON.id}">
<label for="update_code">Class Code</label>
<input type="text" name="code" id="update_code" value="${classAsJSON.code}" required>
<br>
<label for="update_title">Class Title</label>
<input type="text" name="title" id="update_title" value="${classAsJSON.title}">
<br>
<label for="update_description">Class Description</label>
<input type="text" name="description" id="update_description" value="${classAsJSON.description}">
<br>
<label for="update_max_students">Max students in class</label>
<input type="number" name="maxStudents" id="update_max_students" value="${classAsJSON.maxStudents}">
<br>
<button type="submit">Update class details</button>
</form>`;
const idFormUpdateClassDetailsElement = document.getElementById("id_form_update_class_details");
idFormUpdateClassDetailsElement.addEventListener("submit", function(event)
{
event.preventDefault();
const formData = new FormData(idFormUpdateClassDetailsElement);
const classData =
{
id: formData.get("id"),
code: formData.get("code"),
title: formData.get("title"),
description: formData.get("description"),
maxStudents: formData.get("maxStudents")
};
console.log({classData});
updateClass(classData);
});
console.log('handleUpdateClassDetailsEvent - END');
}
async function handleDeleteClassEvent(event)
{
console.log('handleDeleteClassEvent - START');
console.log(`event = ${event}`);
console.log({event});
const classId = event.target.parentElement.getAttribute("data-class-id");
await deleteClass(classId);
console.log('handleDeleteClassEvent - END');
}