db.ts 1.3 KB

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