@neosjs/indexeddb
浏览器端 IndexedDB 封装库,提供基于 Promise 的 API,告别回调地狱。支持多个 ObjectStore 的统一管理、完整的 TypeScript 类型定义、跨 Store 的原子性事务、批量操作与高性能分页,并以统一的 ResponseResult 格式返回结果和错误信息。
安装
sh
pnpm add @neosjs/indexeddbsh
npm i @neosjs/indexeddbsh
yarn add @neosjs/indexeddb快速上手
通过 createDB 创建数据库实例,声明 Store 与索引,然后用 useStore 获取某个 Store 的操作器进行读写:
ts
import { createDB } from '@neosjs/indexeddb'
// 创建数据库实例
const db = createDB('myDatabase', 1, [
{
name: 'users',
keyPath: 'id',
autoIncrement: true,
indexes: [
{ name: 'name', keyPath: 'name' },
{
name: 'email',
keyPath: 'email',
options: { unique: true }
}
]
}
])
// 获取 Store 操作器(支持泛型约束数据结构)
const userStore = db.useStore<{ id: number, name: string, email: string }>('users')
// 添加数据
await userStore.insert({ id: 1, name: 'Alice', email: 'alice@example.com' })
// 查询数据
const result = await userStore.get(1)
console.log(result.data) // { id: 1, name: 'Alice', email: 'alice@example.com' }也可以使用配置对象通过 NeosIndexedDB 类创建实例:
ts
import NeosIndexedDB from '@neosjs/indexeddb'
const db = new NeosIndexedDB({
dbName: 'myDatabase',
version: 1,
stores: [
{
name: 'users',
keyPath: 'id',
autoIncrement: true,
indexes: [
{
name: 'email',
keyPath: 'email',
options: { unique: true }
}
]
}
]
})API
创建实例
| 方法 | 说明 |
|---|---|
createDB(dbName, version, stores) | 快速创建 NeosIndexedDB 实例 |
new NeosIndexedDB(config) | 使用配置对象创建实例(默认导出) |
promisifyRequest(request, errorMsg) | 工具函数:将 IDBRequest 转为 Promise,失败时以 errorMsg 拒绝 |
数据库管理
| 方法 | 说明 |
|---|---|
useStore<T>(storeName) | 获取指定 Store 的操作器 |
runTransaction(storeNames, mode, operation) | 执行自定义事务,支持多 Store、多操作的原子性事务 |
getDBInfo() | 获取数据库信息(名称、版本、Store 列表) |
close() | 关闭数据库连接 |
delete() | 删除整个数据库 |
跨 Store 事务示例:
ts
const result = await db.runTransaction(['users', 'orders'], 'readwrite', async (transaction) => {
const userStore = transaction.objectStore('users')
const orderStore = transaction.objectStore('orders')
// 执行跨 Store 的操作
return someResult
})Store 操作
增加数据
| 方法 | 说明 |
|---|---|
insert(data) | 添加单条数据(主键冲突会失败) |
bulkInsert(dataList, skipError?) | 批量添加数据,返回 { success, failed } 统计 |
查询数据
| 方法 | 说明 |
|---|---|
get(key) | 根据主键获取单条数据 |
getAll() | 获取所有数据 |
getByIndex(indexName, value) | 根据索引查询单条数据 |
getAllByIndex(indexName, range?) | 根据索引查询多条数据,可传 IDBKeyRange |
find(callback, direction?) | 查找第一条符合条件的数据(类似 Array.find) |
exists(key) | 检查主键对应数据是否存在,返回布尔值 |
count(range?) | 获取数据总数 |
更新数据
| 方法 | 说明 |
|---|---|
update(data) | 更新数据(存在则更新,不存在则插入) |
bulkUpdate(dataList, skipError?) | 批量更新数据 |
删除数据
| 方法 | 说明 |
|---|---|
delete(key) | 根据主键删除数据 |
bulkDelete(keys, skipError?) | 批量删除数据 |
clear() | 清空 Store |
遍历与筛选
| 方法 | 说明 |
|---|---|
forEach(callback, direction?) | 游标遍历数据,回调返回 false 可终止遍历 |
map<U>(callback, direction?) | 遍历并转换数据(类似 Array.map) |
filter(callback, direction?) | 遍历并筛选数据(类似 Array.filter) |
分页查询
| 方法 | 说明 |
|---|---|
getPage(options) | 分页查询,返回 PaginationResult |
filterPage(filterCallback, paginationOptions, direction?) | 先筛选,再分页 |
mapPage<U>(mapCallback, paginationOptions, direction?) | 先映射,再分页 |
filterPageHighPerformance(filterCallback, paginationOptions, direction?) | 游标级分页,无需全量收集数据,适合大数据量场景 |
ts
const result = await userStore.getPage({ page: 1, pageSize: 10 })
console.log(result.data)
// {
// list: [...],
// total: 100,
// page: 1,
// pageSize: 10,
// totalPages: 10
// }
// 高性能筛选分页
const result2 = await userStore.filterPageHighPerformance(
item => item.name === 'test',
{ page: 1, pageSize: 10 }
)统一响应格式
所有操作返回统一的 ResponseResult:
ts
interface ResponseResult<T = unknown> {
/** 响应状态码: 0 成功 | 非0 失败 */
code: number
/** 响应数据 */
data?: T
/** 响应消息 */
message?: string
}主要类型定义
ts
// Store 配置
interface StoreConfig {
/** Store 名称 */
name: string
/** 主键字段 */
keyPath: string
/** 是否自增主键 */
autoIncrement?: boolean
/** 索引配置列表 */
indexes?: IndexConfig[]
}
// 索引配置
interface IndexConfig {
/** 索引名称 */
name: string
/** 索引字段(单字段/复合索引) */
keyPath: string | string[]
/** 索引参数(唯一索引/多值索引) */
options?: IDBIndexParameters
}
// 分页查询配置
interface PaginationOptions {
/** 页码(从1开始) */
page: number
/** 每页数量 */
pageSize: number
/** 排序方向(可选) */
direction?: IDBCursorDirection
}