/*
 * @Author: 念一
 * @Date: 2021-05-19 11:49:07
 * @LastEditTime: 2021-05-25 13:57:28
 * @LastEditors: Please set LastEditors
 * @Description: 获取数据库实例
 * @FilePath: /easyvadmin/src/scripts/utils/db/index.ts
 */

const CONFIG = [
  {
    store: 'collectData',
    key: 'id'
  }
];

export const version = 4;

export function getEasyvLocalDB(): Promise<{ success: boolean; data: any }> {
  return new Promise((resolve, reject) => {
    const request = indexedDB.open('EasyvLocalDB', version);
    request.onerror = function (event) {
      console.info('EasyvLocalDB open error', event);
      reject({
        success: false,
        data: event
      });
    };
    request.onsuccess = function (event: any) {
      resolve({
        success: true,
        data: event.target.result
      });
      console.info('EasyvLocalDB open success');
    };
    request.onupgradeneeded = function (event: any) {
      console.info('EasyvLocalDB version update');
      const db = event.target.result;
      CONFIG.forEach((v) => {
        if (!db.objectStoreNames.contains(v.store)) {
          db.createObjectStore(v.store, { keyPath: v.key }); //创建表
        }
      });
      resolve({
        success: true,
        data: db
      });
    };
  });
}
