db.ts 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. import Dexie from 'dexie';
  2. import SystemConst from '@/utils/const';
  3. class DexieDB {
  4. public db: Dexie;
  5. constructor() {
  6. this.db = new Dexie(SystemConst.API_BASE);
  7. // 第一版本考虑动态创建表。但开关数据库造成数据库状态错误。
  8. // 所以改为初始化就创建系统所需要的表。
  9. this.db.version(1).stores({
  10. permission: 'id,name,status,describe,type',
  11. events: 'id,name',
  12. properties: 'id,name',
  13. functions: 'id,name',
  14. tags: 'id,name',
  15. });
  16. }
  17. getDB() {
  18. if (this.db && this.db?.verno === 0) {
  19. // 考虑优化
  20. // 获取不到真实的数据库版本
  21. // 所以当获取到的数据库版本号为0则删除数据库重新初始化
  22. this.db.delete();
  23. this.db = new Dexie(SystemConst.API_BASE);
  24. this.db.version(1);
  25. return this.db;
  26. }
  27. return this.db;
  28. }
  29. /**
  30. * 会造成数据库状态错误
  31. * @deprecated
  32. * @param extendedSchema
  33. */
  34. updateSchema = async (extendedSchema: Record<string, string | null>) => {
  35. await this.getDB().close();
  36. await this.getDB()
  37. .version(this.db.verno + 1)
  38. .stores(extendedSchema);
  39. return this.getDB().open();
  40. };
  41. }
  42. const DB = new DexieDB();
  43. export default DB;