indexdb查询工具r-indexdb

前言

最近将之前做的indexdb工具完善整理了一下,发到了npm上

indexDb 增删改查工具

快速上手

使用 npm 包

npm i r-indexdb -S

在函数中使用

import RIndexDb from 'r-indexdb';
const dbInst = new RIndexDb('dbName',[{name:'tbName',keyPath:'id'}])

async function findById(id){
    await dbInst.ready();
    const ret = await dbInst.findByPk('tbName',id);
    return ret;
}

使用方式

在使用该工具进行增删改查之前,需要先调用 await dbInst.ready()方法等待初始化完毕。

API

获取实例

const dbInst = new RIndexDb(databaseName: string,tbConfigs?: TbConfig[], dbVersion?: number,);

databaseName // 新建或者打开的库名
dbVersion // 库版本号默认为 1
tbConfigs // 库中需要使用的表的配置。

interface TbConfig {
    name: string; // 表名
    autoIncrement?: boolean; // 是否自增主键
    keyPath?: string; // 主键字段
    indexs?: IndexConfig[]; // 表索引配置
}

interface IndexConfig {
    name: string; // 索引名,不能重复
    prop: string; // 在存储对象上的那个属性上建立索引,可以是一个单个的key值,也可以是一个包含key值集合的数组
    config?: {
        unique: boolean; // 用来指定索引值是否可以重复,为true代表不能相同,为false时代表可以相同
        multiEntry: boolean; // 当第二个参数keyPath为一个数组时,如果multiEntry是true,则会以数组中的每个元素建立一条索引,如果是false,则以整个数组为keyPath值,添加一条索引
}

操作数据

1、单条新增数据create
create(tbName: string, data: any): Promise<unknown>;
2、批量新增数据bulkCreate
bulkCreate(tbName: string, datas: any[]): Promise<unknown>;
3、通过主键查找数据findByPk
findByPk(tbName: string, keyPath: string): Promise<unknown>;
4、通过索引查找数据findByIndex
findByIndex(tbName: string, indexName: string, keyPath: string): Promise<unknown>;
5、通过函数过滤查找数据query
query(tbName: string, filter?: (item: any) => boolean): Promise<unknown>;
6、通过主键来更新数据update
update(tbName: string, data: any): Promise<unknown>;
7、通过主键删除数据delete
delete(tbName: string, keyPath: string): Promise<unknown>;
8、如果无法通过主键来更新和删除数据,可以使用 forEachcursor进行操作。
forEach(tbName: string, callback: (cursor: any) => void): Promise<unknown>;

使用cursor.value拿到数据.
使用cursor.updata()更新数据.
使用cursor.delete()删除数据.
使用cursor.continue()读取下一条数据.

9、新增表createStore
createStore(tbName: string, tconfig?: Omit<TbConfig, "name">): IDBObjectStore | undefined;
10、新增索引createIndex
createIndex(tb: string | IDBObjectStore | undefined, index: IndexConfig): boolean;
11、删除表中所有数dropStore
dropStore(tbName: string): Promise<unknown>;

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 一、概述 随着浏览器的功能不断增强,越来越多的网站开始考虑,将大量数据储存在客户端,这样可以减少从服务器获取数据,...
    程序媛_阅读 3,452评论 0 0
  • 现在已经不流行用cookie存储数据了cookie缺点:储存大小太小了,仅4kv左右。单个域名下有数量限制,50个...
    Sallyscript阅读 2,187评论 0 0
  • _________________________________________________________...
    fastwe阅读 4,229评论 0 0
  •   支持离线 Web 应用开发是 HTML5 的另一个重点。   所谓离线 Web 应用,就是在设备不能上网的情况...
    霜天晓阅读 4,729评论 0 2
  • IDBFactory 提供了对数据库的访问。这是由全局对象 indexedDB实现的接口,因而也是该 API 的入...
    幸福镰刀阅读 9,741评论 0 2