Message.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. import TableHelper from './lib/TableHelper'
  2. import User from './User'
  3. class Message extends TableHelper {
  4. constructor () {
  5. super('message')
  6. }
  7. async getMsg (sessionId, limit = 30) {
  8. if (!sessionId) return null
  9. let objTable = await this.getObjTable()
  10. if (!objTable) return
  11. var lowerBound = [sessionId, 0]
  12. var upperBound = [sessionId, 999999999999999]
  13. let keyRangeValue = IDBKeyRange.bound(lowerBound, upperBound)
  14. let cursor = await objTable.index('session_id').openCursor(keyRangeValue, 'prev')
  15. let list = []
  16. let userIds = {}
  17. // let list2 = []
  18. while (cursor && cursor.value) {
  19. let value = cursor.value
  20. if (list.length < limit && value['session_id'] === sessionId) {
  21. list.unshift(value)
  22. userIds[value.from] = value.from
  23. if (value.to) {
  24. userIds[value.to] = value.to
  25. }
  26. cursor = await cursor.continue()
  27. } else {
  28. break
  29. }
  30. }
  31. let objUser = new User()
  32. let userMap = await objUser.getUserMap(userIds)
  33. return { list, userMap }
  34. }
  35. async updatePackInfo (hash, type, value) {
  36. let objTable = await this.getObjTable()
  37. if (!objTable) return
  38. let obj = await objTable.get(hash)
  39. if (obj) {
  40. obj.ext[type] = value
  41. objTable.put(obj)
  42. } else {
  43. console.log('can not find redpack:' + hash)
  44. }
  45. }
  46. async saveMsg (sessionId, data) {
  47. const objMessage = new Message()
  48. // 数据保存到indexDB
  49. let objTable = await objMessage.getObjTable()
  50. if (!objTable) return
  51. for (let key in data.list) {
  52. let value = Object.assign({ 'session_id': sessionId }, data.list[key])
  53. await objTable.put(value)
  54. }
  55. let objUser = new User()
  56. objUser.replaceObjects(data.userMap)
  57. }
  58. async removeMsg (sessionId, hash) {
  59. const objMessage = new Message()
  60. // 数据保存到indexDB
  61. let objTable = await objMessage.getObjTable()
  62. if (!objTable) return
  63. objTable.delete(hash)
  64. }
  65. }
  66. export default Message