IndexDB(treo)实现缓存-TS版本

// 帮助我们更方便操作 indexDB
import treo from "treo";

interface DBIniteData {
  name?: string; // 库名称
  list?: Object[];
}
class DBSchema {
  public db = null;
  public dbCache = {};
  public dbInitPatams: DBIniteData = {
    name: "webDB",
    list: []
  };

  constructor(dbInitPatams: DBIniteData) {
    this.dbInitPatams = dbInitPatams;
    this.initDB(dbInitPatams);
  }

  public addDBCache(tbName: string, data: Object): void {
    if (!this.dbCache[tbName]) {
      this.dbCache[tbName] = [];
    }
    this.dbCache[tbName].push(data);
  }

  public setDBCache(tbName: string, data: Object[]): void {
    this.dbCache[tbName] = data;
  }

  public createDB(): void {
    // list array  { 'version'| 表名称 : 版本号/ 表主键 等 }
    const { name, list = [] } = this.dbInitPatams;
    try {
      // 如果本地没有,则新建chrome
      // schema.version(version) 改变版本
      let schema = treo.schema().version(1);
      // schema.addStore('storage') 创建数据表
      //   schema.addIndex(name, field, opts) 为某一个字段使用name的值添加一个索引 可以在声明一个store之后进行调用 schema.getStore(name) 返回的store中进行调用
      list.map(item => {
        const key = Object.keys(item)[0]; // addStore, addIndex ......
// 注意 这里是解构 所以值需要是一个数组
        schema = schema[key](...item[key]);
      });
      // name 是我们要创建的数据库的名称
      const db = treo(name, schema);
      console.log("开启indexDB数据库成功");
      return db;
    } catch (ex) {
      console.log("创建indexDB失败", ex);
      return this.db;
    }
  }

  public closeDB(cbOk?: Function, cbErr?: Function): void {
    if (this.db && this.db.status === "open") {
      // 如果db存在且是打开状态
      try {
        this.db.close(() => {
          // tslint:disable-next-line:no-unused-expression
          cbOk && cbOk();
          console.log("关闭indexDB数据库成功");
        });
      } catch (ex) {
        // tslint:disable-next-line:no-unused-expression
        cbErr && cbErr();
      }
    }
  }

  /**
   * @description: 初始化DB
   * @param {*} params
   * @return {*}
   */
  public initDB(params: DBIniteData): void {
    this.dbInitPatams = params;
    if (this.db) {
      // 如果存在,则清空本次
      this.closeDB(
        () => {},
        () => {}
      );
      this.db = this.createDB();
    } else {
      // 如果不存在,则直接新建
      this.db = this.createDB();
    }
  }

  public getDB(): void {
    if (!this.db || (this.db && this.db.status === "close")) {
      this.db = this.createDB();
    }
    return this.db;
  }
  /**
   * @description: 插入一条数据
   */
  public putData2DB(tbName: string, dataMap: Object, cb?: Function): void {
    try {
      const store = this.db.store(tbName);
      this.addDBCache(tbName, dataMap);
      return store.put(dataMap, (err, item) => {
        if (err) {
          // tslint:disable-next-line:no-unused-expression
          cb && cb();
        } else {
          // tslint:disable-next-line:no-unused-expression
          cb && cb(item);
        }
      });
    } catch (ex) {}
  }
  /**
   * @description:
   * @param {string} tbName 表名
   * @param {any} data 要插入的数据
   * @return {*}
   */
  public batch2DB(tbName: string, data: Object[]): void {
    try {
      this.setDBCache(tbName, data);
      const store = this.db.store(tbName);
      return store.batch(data, err => {
        console.log(err);
      });
    } catch (ex) {}
  }

  public getListFromDB(tbName: string, cb?: Function): void {
    try {
      if (this.dbCache[tbName]) {
        // tslint:disable-next-line:no-unused-expression
        cb && cb(this.dbCache[tbName]);
        return;
      }
      const store = this.db.store(tbName);
      return store.all((err, items) => {
        // tslint:disable-next-line:no-unused-expression
        cb && cb(items);
        this.setDBCache(tbName, items);
      });
    } catch (ex) {}
  }

  /**
   * @description: 读取一条数据
   * @param {string} tbName 表名称
   * @param {string} name 表里 字段
   * @param {string} data 该字段的值
   * @param {*} cb 回调函数
   * @return {*}
   */
  public getDataFromDB(
    tbName: string,
    name: string,
    data: string | number,
    cb?: Function
  ): void {
    try {
      if (this.dbCache[tbName]) {
        //  从内存里读取
        const item = this.dbCache[tbName].find(rowData => {
          return rowData[name] === data;
        });
        // tslint:disable-next-line:no-unused-expression
        cb && cb(item);
        return;
      }
      const store = this.db.store(tbName);
      return store.index(name).get(data, (err, item) => {
        if (err) {
          // tslint:disable-next-line:no-unused-expression
          cb && cb();
        } else {
          this.addDBCache(tbName, item);
          // tslint:disable-next-line:no-unused-expression
          cb && cb(item);
        }
      });
    } catch (ex) {}
  }
}

// 示例数据

// {
//     name: 'linDB',
//     list: [
//       { version: 1 },
//       {
//         addStore: ['appInfoList', { key: 'id' }],
//       },
//       { addIndex: ['byId', 'id'] },
//       { addIndex: ['byAge', 'age'] },
//     ],
//   };
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容