一個簡單的 indexedDB 應用示例

HorseShoe2016發表於2024-04-09

現代瀏覽器中會包含 indexedDB,這是一個功能比 localStorage 更加強大的資料庫引擎,其 API 描述詳見 W3規範:IndexedDB

如下是一個簡單的應用示例:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <script src="https://cdn.jsdelivr.net/npm/idb@3.0.2/build/idb.min.js"></script>
    <title>IndexedDB BookStore</title>
  </head>
  <body>
    <button onclick="addBook()">Add a book</button>
    <button onclick="clearBooks()">Clear books</button>

    <p>Books list:</p>

    <ul id="listElem"></ul>

    <script>
      let db

      init()

      async function init() {
        // 這裡的 idb 就是 'https://cdn.jsdelivr.net/npm/idb@3.0.2/build/idb.min.js' 生成的
        // indexedDB 的別名
        db = await idb.openDb('booksDb', 1, (db) => {
          db.createObjectStore('books', { keyPath: 'name' })
        })

        list()
      }

      async function list() {
        let tx = db.transaction('books')
        let bookStore = tx.objectStore('books')

        let books = await bookStore.getAll()

        if (books.length) {
          listElem.innerHTML = books
            .map(
              (book) => `<li>
        name: ${book.name}, price: ${book.price}
      </li>`
            )
            .join('')
        } else {
          listElem.innerHTML = '<li>No books yet. Please add books.</li>'
        }
      }

      async function clearBooks() {
        let tx = db.transaction('books', 'readwrite')
        await tx.objectStore('books').clear()
        await list()
      }

      async function addBook() {
        let name = prompt('Book name?')
        let price = +prompt('Book price?')

        let tx = db.transaction('books', 'readwrite')

        try {
          await tx.objectStore('books').add({ name, price })
          await list()
        } catch (err) {
          if (err.name == 'ConstraintError') {
            alert('Such book exists already')
            await addBook()
          } else {
            throw err
          }
        }
      }

      window.addEventListener('unhandledrejection', (event) => {
        alert('Error: ' + event.reason.message)
      })
    </script>
  </body>
</html>

相關文章