DB.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. import { openDb } from 'idb'
  2. let objDb = null
  3. class DB {
  4. static curDBUserId = localStorage.getItem('user_id');
  5. static async initDb () {
  6. let userId = localStorage.getItem('user_id')
  7. if (!objDb || DB.curDBUserId != userId) {
  8. // 切换用户
  9. if (DB.curDBUserId != userId) DB.curDBUserId = userId
  10. objDb = await initDb()
  11. }
  12. return objDb
  13. }
  14. static async init (tableName) {
  15. await DB.initDb()
  16. if (objDb) {
  17. return objDb.transaction(tableName, 'readwrite').objectStore(tableName)
  18. } else {
  19. return null
  20. }
  21. }
  22. }
  23. async function initDb () {
  24. let userId = DB.curDBUserId
  25. if (!userId) return null
  26. let dbName = `database_${userId}`
  27. let version = 3
  28. let objDb = await openDb(dbName, version, upgradeDB => {
  29. console.log(`oldVersion:${upgradeDB.oldVersion}, version:${version}`)
  30. // Note: we don't use 'break' in this switch statement,
  31. // the fall-through behaviour is what we want.
  32. switch (upgradeDB.oldVersion) {
  33. case 0:
  34. let objMessage = upgradeDB.createObjectStore('message', { keyPath: 'hash' })
  35. objMessage.createIndex('group_id', 'group_id', { unique: false })
  36. objMessage.createIndex('msg_num', 'msg_num', { unique: false })
  37. objMessage.createIndex('create_time_int', 'create_time_int', { unique: false })
  38. let objUser = upgradeDB.createObjectStore('user', { keyPath: 'user_id' })
  39. objUser.createIndex('user_name', 'user_name', { unique: true })
  40. objUser.createIndex('nick_name', 'nick_name', { unique: false })
  41. objUser.createIndex('is_admin', 'is_admin', { unique: false })
  42. objUser.createIndex('is_block', 'is_block', { unique: false })
  43. // falls through
  44. case 1:
  45. let objSession = upgradeDB.createObjectStore('session', { keyPath: 'session_id' })
  46. objSession.createIndex('pin_time_int', ['pin_time_int', 'update_time_int'], { unique: false })
  47. objSession.createIndex('is_pin', 'is_pin', { unique: false })
  48. objSession.createIndex('update_time_int', 'update_time_int', { unique: false })
  49. // falls through
  50. case 2:
  51. objMessage = upgradeDB.transaction.objectStore('message')
  52. objMessage.deleteIndex('group_id')
  53. objMessage.createIndex('session_id', ['session_id', 'create_time_int'], { unique: false })
  54. }
  55. }).catch(function (ex) {
  56. console.error('initDb error:' + ex.message)
  57. // alert('initDb error:' + ex.message)
  58. })
  59. return objDb
  60. }
  61. export default DB