database.ts 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. import Dexie from 'dexie'
  2. import { databaseId } from '@/store/main'
  3. import type { Slide } from '@/types/slides'
  4. import { LOCALSTORAGE_KEY_DISCARDED_DB } from '@/configs/storage'
  5. export interface writingBoardImg {
  6. id: string
  7. dataURL: string
  8. }
  9. export interface Snapshot {
  10. index: number
  11. slides: Slide[]
  12. }
  13. const databaseNamePrefix = 'PPT'
  14. // 删除失效/过期的数据库
  15. // 应用关闭时(关闭或刷新浏览器),会将其数据库ID记录在 localStorage 中,表示该ID指向的数据库已失效
  16. // 当应用初始化时,检查当前所有数据库,将被记录失效的数据库删除
  17. // 另外,距离初始化时间超过12小时的数据库也将被删除(这是为了防止出现因意外未被正确删除的库)
  18. export const deleteDiscardedDB = async () => {
  19. const now = new Date().getTime()
  20. const localStorageDiscardedDB = localStorage.getItem(LOCALSTORAGE_KEY_DISCARDED_DB)
  21. const localStorageDiscardedDBList: string[] = localStorageDiscardedDB ? JSON.parse(localStorageDiscardedDB) : []
  22. const databaseNames = await Dexie.getDatabaseNames()
  23. const discardedDBNames = databaseNames.filter(name => {
  24. if (name.indexOf(databaseNamePrefix) === -1) return false
  25. const [prefix, id, time] = name.split('_')
  26. if (prefix !== databaseNamePrefix || !id || !time) return true
  27. if (localStorageDiscardedDBList.includes(id)) return true
  28. if (now - (+time) >= 1000 * 60 * 60 * 12) return true
  29. return false
  30. })
  31. for (const name of discardedDBNames) Dexie.delete(name)
  32. localStorage.removeItem(LOCALSTORAGE_KEY_DISCARDED_DB)
  33. }
  34. class PPTistDB extends Dexie {
  35. public snapshots: Dexie.Table<Snapshot, number>
  36. public writingBoardImgs: Dexie.Table<writingBoardImg, number>
  37. public constructor() {
  38. super(`${databaseNamePrefix}_${databaseId}_${new Date().getTime()}`)
  39. this.version(1).stores({
  40. snapshots: '++id',
  41. writingBoardImgs: '++id',
  42. })
  43. this.snapshots = this.table('snapshots')
  44. this.writingBoardImgs = this.table('writingBoardImgs')
  45. }
  46. }
  47. export const db = new PPTistDB()