database.ts 1.9 KB

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