Skip to content

快速开始

IndexedDB你可以理解为
database数据库
objectStore
key主键
value

创建“数据库” 与 “表”

ts
import { openDB } from "idb";

const db = await openDB("my-db", 1, {
  // 类似表
  upgrade(db) {
    db.createObjectStore("posts", {
      keyPath: "id", // 主键字段
      autoIncrement: true, // 自增
    });
  },
});

cursor 分页

ts
async function listPosts(page: number, pageSize: number) {
  const db = await dbPromise

  const total = await db.count('posts')

  const tx = db.transaction('posts')
  let cursor = await tx.store.openCursor()

  const offset = (page - 1) * pageSize
  const list = []

  let skipped = 0

  while (cursor && skipped < offset) {
    skipped++
    cursor = await cursor.continue()
  }

  while (cursor && list.length < pageSize) {
    list.push(cursor.value)
    cursor = await cursor.continue()
  }

  return {
    total,
    page,
    pageSize,
    list,
  }
}

基于索引分页

ts
async function listPostsByStatus(
  status: string,
  page: number,
  pageSize: number
) {
  const db = await dbPromise
  const tx = db.transaction('posts')
  const index = tx.store.index('by-status')

  const total = await index.count(status)

  const list = []
  let cursor = await index.openCursor(status)

  let offset = (page - 1) * pageSize

  while (cursor && offset > 0) {
    offset--
    cursor = await cursor.continue()
  }

  while (cursor && list.length < pageSize) {
    list.push(cursor.value)
    cursor = await cursor.continue()
  }

  await tx.done

  return {
    total,
    page,
    pageSize,
    list,
  }
}

key range 分页

ts
async function listByCursor(lastId?: number, limit = 10) {
  const db = await dbPromise

  const range = lastId
    ? IDBKeyRange.lowerBound(lastId, true)
    : undefined

  const list = await db.getAll('posts', range, limit)

  return list
}

事物

ts
const tx = db.transaction("auth", "readwrite");

await tx.store.put("token1", "k1");

await tx.store.put("token2", "k2");

await tx.done;