Repository navigation
Expand file tree
/
Copy pathapp.js
More file actions
796 lines (664 loc) Β· 21.3 KB
/
Copy pathapp.js
File metadata and controls
796 lines (664 loc) Β· 21.3 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
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
/**
* ===========================================
* Library Manager - Frontend JavaScript
* Session 18: Connecting Frontend to API
* ===========================================
*
* This file contains all the JavaScript needed to connect
* your frontend to your C# Library API using fetch()!
*
* WHAT YOU'LL LEARN:
* - fetch() API for HTTP requests
* - async/await for handling promises
* - Loading states and error handling
* - Full CRUD operations (Create, Read, Update, Delete)
*/
// ===========================================
// CONFIGURATION
// ===========================================
/**
* Change this URL to match where your C# API is running!
*
* To find your API URL:
* 1. Run your C# API with 'dotnet run'
* 2. Look for "Now listening on: http://localhost:XXXX"
* 3. Use that URL here (with /api at the end)
*/
const API_BASE_URL = 'http://localhost:5000/api';
// Store for all books (cache)
let allBooks = [];
// ===========================================
// INITIALIZATION
// ===========================================
/**
* When the page loads, set everything up and load books
*/
document.addEventListener('DOMContentLoaded', () => {
console.log('Library Manager initializing...');
// Set up event listeners
setupFormHandlers();
setupSearchHandler();
setupFilterHandlers();
// Load books from API
loadBooks();
});
// ===========================================
// API FUNCTIONS - The Core of This Lesson!
// ===========================================
/**
* GET all books from the API
*
* This is the most basic fetch() call.
* fetch() returns a Promise, and we use async/await to handle it.
*/
async function loadBooks() {
console.log('Loading books from API...');
showLoading();
updateConnectionStatus('checking');
try {
// Step 1: Make the GET request
// fetch() sends an HTTP request and returns a Promise
const response = await fetch(`${API_BASE_URL}/books`);
// Step 2: Check if the request was successful
// HTTP status codes 200-299 are considered "ok"
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
// Step 3: Parse the JSON response
// response.json() also returns a Promise, so we await it
const books = await response.json();
// Step 4: Store and display the books
allBooks = books;
displayBooks(books);
updateConnectionStatus('connected');
console.log(`Loaded ${books.length} books`);
} catch (error) {
// Handle any errors (network issues, API down, etc.)
console.error('Failed to load books:', error);
showError(error.message);
updateConnectionStatus('disconnected');
}
}
/**
* POST - Create a new book
*
* POST requests send data TO the server to create something new.
* We need to:
* 1. Set method to 'POST'
* 2. Set Content-Type header to tell the server we're sending JSON
* 3. Include the data in the body as a JSON string
*/
async function createBook(bookData) {
console.log('Creating book:', bookData);
try {
const response = await fetch(`${API_BASE_URL}/books`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(bookData)
});
// Handle validation errors from the API
if (!response.ok) {
const errorData = await response.json();
// ASP.NET Core returns validation errors in a specific format
if (errorData.errors) {
const messages = Object.values(errorData.errors).flat();
throw new Error(messages.join(', '));
}
throw new Error(errorData.title || 'Failed to create book');
}
const newBook = await response.json();
console.log('Book created:', newBook);
// Refresh the list to show the new book
await loadBooks();
// Show success message
showToast('Book added successfully!', 'success');
return newBook;
} catch (error) {
console.error('Failed to create book:', error);
showToast(error.message, 'error');
throw error;
}
}
/**
* PUT - Update an existing book
*
* PUT requests update existing data on the server.
* We include the ID in the URL to specify which book to update.
*/
async function updateBook(id, bookData) {
console.log(`Updating book ${id}:`, bookData);
try {
const response = await fetch(`${API_BASE_URL}/books/${id}`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(bookData)
});
if (!response.ok) {
const errorData = await response.json();
throw new Error(errorData.title || 'Failed to update book');
}
const updatedBook = await response.json();
console.log('Book updated:', updatedBook);
// Refresh the list
await loadBooks();
showToast('Book updated successfully!', 'success');
return updatedBook;
} catch (error) {
console.error('Failed to update book:', error);
showToast(error.message, 'error');
throw error;
}
}
/**
* DELETE - Remove a book
*
* DELETE requests remove data from the server.
* The ID in the URL specifies which book to delete.
*/
async function deleteBook(id) {
console.log(`Deleting book ${id}`);
try {
const response = await fetch(`${API_BASE_URL}/books/${id}`, {
method: 'DELETE'
});
if (!response.ok) {
throw new Error('Failed to delete book');
}
console.log(`Book ${id} deleted`);
// Refresh the list
await loadBooks();
showToast('Book deleted successfully!', 'success');
} catch (error) {
console.error('Failed to delete book:', error);
showToast(error.message, 'error');
throw error;
}
}
/**
* POST - Checkout a book
*
* This is a custom action endpoint on our API.
*/
async function checkoutBook(id) {
console.log(`Checking out book ${id}`);
try {
const response = await fetch(`${API_BASE_URL}/books/${id}/checkout`, {
method: 'POST'
});
if (!response.ok) {
const errorData = await response.json();
throw new Error(errorData || 'Failed to checkout book');
}
// Refresh the list
await loadBooks();
showToast('Book checked out!', 'success');
} catch (error) {
console.error('Failed to checkout book:', error);
showToast(error.message, 'error');
}
}
/**
* POST - Return a book
*/
async function returnBook(id) {
console.log(`Returning book ${id}`);
try {
const response = await fetch(`${API_BASE_URL}/books/${id}/return`, {
method: 'POST'
});
if (!response.ok) {
const errorData = await response.json();
throw new Error(errorData || 'Failed to return book');
}
// Refresh the list
await loadBooks();
showToast('Book returned!', 'success');
} catch (error) {
console.error('Failed to return book:', error);
showToast(error.message, 'error');
}
}
/**
* GET - Fetch a single book by ID
*
* Used to populate the edit form.
*/
async function getBook(id) {
try {
const response = await fetch(`${API_BASE_URL}/books/${id}`);
if (!response.ok) {
throw new Error('Book not found');
}
return await response.json();
} catch (error) {
console.error('Failed to get book:', error);
throw error;
}
}
// ===========================================
// UI STATE FUNCTIONS
// ===========================================
/**
* Show the loading spinner
*/
function showLoading() {
document.getElementById('loading').classList.remove('hidden');
document.getElementById('booksList').classList.add('hidden');
document.getElementById('error').classList.add('hidden');
document.getElementById('emptyState').classList.add('hidden');
}
/**
* Show the books list
*/
function showBooks() {
document.getElementById('loading').classList.add('hidden');
document.getElementById('booksList').classList.remove('hidden');
document.getElementById('error').classList.add('hidden');
document.getElementById('emptyState').classList.add('hidden');
}
/**
* Show an error message
*/
function showError(message) {
document.getElementById('loading').classList.add('hidden');
document.getElementById('booksList').classList.add('hidden');
document.getElementById('error').classList.remove('hidden');
document.getElementById('emptyState').classList.add('hidden');
document.getElementById('errorMessage').textContent = message;
}
/**
* Show empty state when no books exist
*/
function showEmptyState() {
document.getElementById('loading').classList.add('hidden');
document.getElementById('booksList').classList.add('hidden');
document.getElementById('error').classList.add('hidden');
document.getElementById('emptyState').classList.remove('hidden');
}
/**
* Update the connection status indicator
*/
function updateConnectionStatus(status) {
const statusElement = document.getElementById('connectionStatus');
const statusText = statusElement.querySelector('.status-text');
statusElement.classList.remove('connected', 'disconnected');
switch (status) {
case 'connected':
statusElement.classList.add('connected');
statusText.textContent = 'Connected to API';
break;
case 'disconnected':
statusElement.classList.add('disconnected');
statusText.textContent = 'API Disconnected';
break;
default:
statusText.textContent = 'Checking connection...';
}
}
// ===========================================
// DISPLAY FUNCTIONS
// ===========================================
/**
* Display books in the grid
*/
function displayBooks(books) {
const booksList = document.getElementById('booksList');
// Show empty state if no books
if (books.length === 0) {
showEmptyState();
return;
}
// Clear existing books
booksList.innerHTML = '';
// Create a card for each book
books.forEach(book => {
const bookCard = createBookCard(book);
booksList.appendChild(bookCard);
});
showBooks();
}
/**
* Create a single book card element
*/
function createBookCard(book) {
const card = document.createElement('div');
card.className = `book-card ${book.isAvailable ? '' : 'checked-out'}`;
card.dataset.bookId = book.id;
card.innerHTML = `
<h3>${escapeHtml(book.title)}</h3>
<p class="author">${escapeHtml(book.author)}</p>
<p class="pages">${book.pageCount} pages</p>
<span class="status ${book.isAvailable ? 'available' : 'checked-out'}">
${book.isAvailable ? 'Available' : 'Checked Out'}
</span>
<div class="book-actions">
<button class="btn btn-secondary btn-small" onclick="openEditModal(${book.id})">
Edit
</button>
<button class="btn btn-danger btn-small" onclick="openDeleteModal(${book.id}, '${escapeHtml(book.title)}')">
Delete
</button>
${book.isAvailable
? `<button class="btn btn-success btn-small" onclick="checkoutBook(${book.id})">
Checkout
</button>`
: `<button class="btn btn-primary btn-small" onclick="returnBook(${book.id})">
Return
</button>`
}
</div>
`;
return card;
}
/**
* Escape HTML to prevent XSS attacks
*
* SECURITY NOTE: Always escape user-provided data before
* inserting it into the DOM!
*/
function escapeHtml(text) {
const div = document.createElement('div');
div.textContent = text;
return div.innerHTML;
}
// ===========================================
// FORM HANDLERS
// ===========================================
/**
* Set up form submission handlers
*/
function setupFormHandlers() {
// Add book form
const addForm = document.getElementById('addBookForm');
addForm.addEventListener('submit', handleAddBook);
// Edit book form
const editForm = document.getElementById('editBookForm');
editForm.addEventListener('submit', handleEditBook);
}
/**
* Handle the add book form submission
*/
async function handleAddBook(event) {
event.preventDefault();
const form = event.target;
const submitButton = form.querySelector('button[type="submit"]');
// Get form data
const bookData = {
title: document.getElementById('title').value.trim(),
author: document.getElementById('author').value.trim(),
pageCount: parseInt(document.getElementById('pageCount').value, 10)
};
// Validate
if (!bookData.title || !bookData.author || isNaN(bookData.pageCount)) {
showToast('Please fill in all fields correctly', 'error');
return;
}
// Show loading state on button
setButtonLoading(submitButton, true);
try {
await createBook(bookData);
// Clear the form on success
form.reset();
} catch (error) {
// Error is already handled in createBook()
} finally {
setButtonLoading(submitButton, false);
}
}
/**
* Handle the edit book form submission
*/
async function handleEditBook(event) {
event.preventDefault();
const form = event.target;
const submitButton = form.querySelector('button[type="submit"]');
const bookId = document.getElementById('editBookId').value;
const bookData = {
title: document.getElementById('editTitle').value.trim(),
author: document.getElementById('editAuthor').value.trim(),
pageCount: parseInt(document.getElementById('editPageCount').value, 10)
};
setButtonLoading(submitButton, true);
try {
await updateBook(bookId, bookData);
closeModal();
} catch (error) {
// Error is already handled in updateBook()
} finally {
setButtonLoading(submitButton, false);
}
}
/**
* Toggle button loading state
*/
function setButtonLoading(button, isLoading) {
const buttonText = button.querySelector('.button-text');
const spinner = button.querySelector('.spinner');
if (isLoading) {
buttonText.classList.add('hidden');
spinner.classList.remove('hidden');
button.disabled = true;
} else {
buttonText.classList.remove('hidden');
spinner.classList.add('hidden');
button.disabled = false;
}
}
// ===========================================
// SEARCH & FILTER
// ===========================================
/**
* Set up the search input handler
*/
function setupSearchHandler() {
const searchInput = document.getElementById('searchInput');
// Use 'input' event for real-time filtering
searchInput.addEventListener('input', filterBooks);
}
/**
* Set up filter radio button handlers
*/
function setupFilterHandlers() {
const filterInputs = document.querySelectorAll('input[name="filter"]');
filterInputs.forEach(input => {
input.addEventListener('change', filterBooks);
});
}
/**
* Filter and display books based on search and filter
*/
function filterBooks() {
const searchTerm = document.getElementById('searchInput').value.toLowerCase();
const filterValue = document.querySelector('input[name="filter"]:checked').value;
let filteredBooks = allBooks;
// Apply search filter
if (searchTerm) {
filteredBooks = filteredBooks.filter(book =>
book.title.toLowerCase().includes(searchTerm) ||
book.author.toLowerCase().includes(searchTerm)
);
}
// Apply availability filter
if (filterValue === 'available') {
filteredBooks = filteredBooks.filter(book => book.isAvailable);
} else if (filterValue === 'checked-out') {
filteredBooks = filteredBooks.filter(book => !book.isAvailable);
}
displayBooks(filteredBooks);
}
// ===========================================
// MODAL HANDLERS
// ===========================================
/**
* Open the edit modal and populate with book data
*/
async function openEditModal(bookId) {
const modal = document.getElementById('editModal');
try {
const book = await getBook(bookId);
document.getElementById('editBookId').value = book.id;
document.getElementById('editTitle').value = book.title;
document.getElementById('editAuthor').value = book.author;
document.getElementById('editPageCount').value = book.pageCount;
modal.classList.remove('hidden');
} catch (error) {
showToast('Failed to load book details', 'error');
}
}
/**
* Close the edit modal
*/
function closeModal() {
const modal = document.getElementById('editModal');
modal.classList.add('hidden');
// Reset the form
document.getElementById('editBookForm').reset();
}
/**
* Open the delete confirmation modal
*/
function openDeleteModal(bookId, bookTitle) {
const modal = document.getElementById('deleteModal');
const titleSpan = document.getElementById('deleteBookTitle');
const confirmBtn = document.getElementById('confirmDeleteBtn');
titleSpan.textContent = bookTitle;
// Set up the confirm button
confirmBtn.onclick = async () => {
setButtonLoading(confirmBtn, true);
try {
await deleteBook(bookId);
closeDeleteModal();
} catch (error) {
// Error handled in deleteBook()
} finally {
setButtonLoading(confirmBtn, false);
}
};
modal.classList.remove('hidden');
}
/**
* Close the delete confirmation modal
*/
function closeDeleteModal() {
const modal = document.getElementById('deleteModal');
modal.classList.add('hidden');
}
// ===========================================
// TOAST NOTIFICATIONS
// ===========================================
/**
* Show a toast notification
*/
function showToast(message, type = 'info') {
const toast = document.getElementById('toast');
const toastMessage = toast.querySelector('.toast-message');
const toastIcon = toast.querySelector('.toast-icon');
// Set message and type
toastMessage.textContent = message;
toast.className = `toast ${type}`;
// Set icon based on type
switch (type) {
case 'success':
toastIcon.textContent = '\u2713'; // checkmark
break;
case 'error':
toastIcon.textContent = '\u2717'; // X mark
break;
default:
toastIcon.textContent = '\u2139'; // info
}
// Show toast
toast.classList.remove('hidden');
// Auto-hide after 3 seconds
setTimeout(() => {
toast.classList.add('hidden');
}, 3000);
}
// ===========================================
// KEYBOARD SHORTCUTS
// ===========================================
/**
* Handle keyboard shortcuts
*/
document.addEventListener('keydown', (event) => {
// Escape key closes modals
if (event.key === 'Escape') {
closeModal();
closeDeleteModal();
}
});
// ===========================================
// CONSOLE HELPERS (For Learning!)
// ===========================================
/**
* These functions let you practice fetch() in the browser console!
*
* Try typing these in the browser console (F12 > Console):
*
* > testGet()
* > testPost()
* > testPut(1)
* > testDelete(1)
*/
window.testGet = async function() {
console.log('Testing GET all books...');
const response = await fetch(`${API_BASE_URL}/books`);
const data = await response.json();
console.log('Response:', data);
return data;
};
window.testPost = async function() {
console.log('Testing POST new book...');
const response = await fetch(`${API_BASE_URL}/books`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
title: 'Test Book from Console',
author: 'Console Tester',
pageCount: 100
})
});
const data = await response.json();
console.log('Response:', data);
loadBooks(); // Refresh the UI
return data;
};
window.testPut = async function(id) {
console.log(`Testing PUT update book ${id}...`);
const response = await fetch(`${API_BASE_URL}/books/${id}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
title: 'Updated from Console'
})
});
const data = await response.json();
console.log('Response:', data);
loadBooks(); // Refresh the UI
return data;
};
window.testDelete = async function(id) {
console.log(`Testing DELETE book ${id}...`);
const response = await fetch(`${API_BASE_URL}/books/${id}`, {
method: 'DELETE'
});
console.log('Status:', response.status);
loadBooks(); // Refresh the UI
return response.ok;
};
console.log(`
===========================================
Library Manager - Frontend Loaded!
===========================================
Try these in the console:
testGet() - Get all books
testPost() - Create a new book
testPut(1) - Update book with ID 1
testDelete(1) - Delete book with ID 1
API URL: ${API_BASE_URL}
===========================================
`);