|
| 1 | +<!doctype html> |
| 2 | +<script src="https://cdn.jsdelivr.net/npm/idb@3.0.2/build/idb.min.js"></script> |
| 3 | + |
| 4 | +<button onclick="addBook()">Add a book</button> |
| 5 | +<button onclick="clearBooks()">Clear books</button> |
| 6 | + |
| 7 | +<p>Books list:</p> |
| 8 | + |
| 9 | +<ul id="listElem"></ul> |
| 10 | + |
| 11 | +<script> |
| 12 | +let db; |
| 13 | + |
| 14 | +init(); |
| 15 | + |
| 16 | +async function init() { |
| 17 | + db = await idb.openDb('booksDb', 1, db => { |
| 18 | + db.createObjectStore('books', {keyPath: 'name'}); |
| 19 | + }); |
| 20 | + |
| 21 | + list(); |
| 22 | +} |
| 23 | + |
| 24 | +async function list() { |
| 25 | + let tx = db.transaction('books'); |
| 26 | + let bookStore = tx.objectStore('books'); |
| 27 | + |
| 28 | + let books = await bookStore.getAll(); |
| 29 | + |
| 30 | + if (books.length) { |
| 31 | + listElem.innerHTML = books.map(book => `<li> |
| 32 | + name: ${book.name}, price: ${book.price} |
| 33 | + </li>`).join(''); |
| 34 | + } else { |
| 35 | + listElem.innerHTML = '<li>No books yet. Please add books.</li>' |
| 36 | + } |
| 37 | + |
| 38 | + |
| 39 | +} |
| 40 | + |
| 41 | +async function clearBooks() { |
| 42 | + let tx = db.transaction('books', 'readwrite'); |
| 43 | + await tx.objectStore('books').clear(); |
| 44 | + await list(); |
| 45 | +} |
| 46 | + |
| 47 | +async function addBook() { |
| 48 | + let name = prompt("Book name?"); |
| 49 | + let price = +prompt("Book price?"); |
| 50 | + |
| 51 | + let tx = db.transaction('books', 'readwrite'); |
| 52 | + |
| 53 | + try { |
| 54 | + await tx.objectStore('books').add({name, price}); |
| 55 | + await list(); |
| 56 | + } catch(err) { |
| 57 | + if (err.name == 'ConstraintError') { |
| 58 | + alert("Such book exists already"); |
| 59 | + await addBook(); |
| 60 | + } else { |
| 61 | + throw err; |
| 62 | + } |
| 63 | + } |
| 64 | +} |
| 65 | + |
| 66 | +window.addEventListener('unhandledrejection', event => { |
| 67 | + alert("Error: " + event.reason.message); |
| 68 | +}); |
| 69 | + |
| 70 | +</script> |
0 commit comments