golang-im聊天
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

90 lines
2.4 KiB

  1. package repo
  2. import (
  3. "fmt"
  4. "gim/internal/business/comm/utils"
  5. "gim/internal/logic/domain/message/model"
  6. "gim/pkg/db"
  7. "gim/pkg/gerrors"
  8. "time"
  9. )
  10. const messageTableNum = 1
  11. type messageRepo struct{}
  12. var MessageRepo = new(messageRepo)
  13. func (*messageRepo) tableName(userId int64) string {
  14. return fmt.Sprintf("message_%03d", userId%messageTableNum)
  15. //return "message"
  16. }
  17. // Save 插入一条消息
  18. func (d *messageRepo) Save(message model.Message) error {
  19. err := db.DB.Table(d.tableName(message.UserId)).Create(&message).Error
  20. if err != nil {
  21. return gerrors.WrapError(err)
  22. }
  23. return nil
  24. }
  25. // ListBySeq 根据类型和id查询大于序号大于seq的消息
  26. func (d *messageRepo) ListBySeq(userId, seq, limit int64) ([]model.Message, bool, error) {
  27. DB := db.DB.Table(d.tableName(userId)).
  28. Where("user_id = ? and seq > ?", userId, seq)
  29. var count int64
  30. err := DB.Count(&count).Error
  31. if err != nil {
  32. return nil, false, gerrors.WrapError(err)
  33. }
  34. if count == 0 {
  35. return nil, false, nil
  36. }
  37. var messages []model.Message
  38. err = DB.Limit(limit).Find(&messages).Error
  39. if err != nil {
  40. return nil, false, gerrors.WrapError(err)
  41. }
  42. return messages, count > limit, nil
  43. }
  44. // GetMessage 获取消息状态
  45. func (d *messageRepo) GetMessage(senderId, seq int64) (*model.Message, error) {
  46. var message model.Message
  47. if err := db.DB.Table(d.tableName(senderId)).Where("user_id = ? and seq = ?", senderId, seq).
  48. First(&message).Error; err != nil {
  49. return nil, gerrors.WrapError(err)
  50. }
  51. return &message, nil
  52. }
  53. // GetMessageSeqForSendTime 获取消息状态
  54. func (d *messageRepo) GetMessageSeqForSendTime(userId int64, sendTime time.Time) (int64, error) {
  55. var message model.Message
  56. if err := db.DB.Table(d.tableName(userId)).Where("user_id = ? and send_time = ?", userId, sendTime).
  57. First(&message).Error; err != nil {
  58. return 0, gerrors.WrapError(err)
  59. }
  60. utils.FilePutContents("GetMessageSeqForSendTime", utils.SerializeStr(map[string]interface{}{
  61. "userId": userId,
  62. "sendTime": sendTime,
  63. "message": message,
  64. "seq": message.Seq,
  65. }))
  66. return message.Seq, nil
  67. }
  68. // UpdateStatus 更新消息状态
  69. func (d *messageRepo) UpdateStatus(userId int64, sendTime time.Time, status int) (int64, error) {
  70. db := db.DB.Model(&model.Message{}).Table(d.tableName(userId)).Where("user_id = ? and send_time = ?", userId, sendTime).
  71. Update("status", status)
  72. if db.Error != nil {
  73. return 0, gerrors.WrapError(db.Error)
  74. }
  75. return db.RowsAffected, nil
  76. }