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.
 
 
 
 

89 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. }
  16. // Save 插入一条消息
  17. func (d *messageRepo) Save(message model.Message) error {
  18. err := db.DB.Table(d.tableName(message.UserId)).Create(&message).Error
  19. if err != nil {
  20. return gerrors.WrapError(err)
  21. }
  22. return nil
  23. }
  24. // ListBySeq 根据类型和id查询大于序号大于seq的消息
  25. func (d *messageRepo) ListBySeq(userId, seq, limit int64) ([]model.Message, bool, error) {
  26. DB := db.DB.Table(d.tableName(userId)).
  27. Where("user_id = ? and seq > ?", userId, seq)
  28. var count int64
  29. err := DB.Count(&count).Error
  30. if err != nil {
  31. return nil, false, gerrors.WrapError(err)
  32. }
  33. if count == 0 {
  34. return nil, false, nil
  35. }
  36. var messages []model.Message
  37. err = DB.Limit(limit).Find(&messages).Error
  38. if err != nil {
  39. return nil, false, gerrors.WrapError(err)
  40. }
  41. return messages, count > limit, nil
  42. }
  43. // GetMessage 获取消息状态
  44. func (d *messageRepo) GetMessage(senderId, seq int64) (*model.Message, error) {
  45. var message model.Message
  46. if err := db.DB.Where("sender_id = ? and seq = ?", senderId, seq).
  47. First(&message).Error; err != nil {
  48. return nil, gerrors.WrapError(err)
  49. }
  50. return &message, nil
  51. }
  52. // GetMessageSeqForSendTime 获取消息状态
  53. func (d *messageRepo) GetMessageSeqForSendTime(userId int64, sendTime time.Time) (int64, error) {
  54. var message model.Message
  55. if err := db.DB.Table(d.tableName(userId)).Where("user_id = ? and send_time = ?", userId, sendTime).
  56. First(&message).Error; err != nil {
  57. return 0, gerrors.WrapError(err)
  58. }
  59. utils.FilePutContents("GetMessageSeqForSendTime", utils.SerializeStr(map[string]interface{}{
  60. "userId": userId,
  61. "sendTime": sendTime,
  62. "message": message,
  63. "seq": message.Seq,
  64. }))
  65. return message.Seq, nil
  66. }
  67. // UpdateStatus 更新消息状态
  68. func (d *messageRepo) UpdateStatus(userId int64, sendTime time.Time, status int) (int64, error) {
  69. db := db.DB.Model(&model.Message{}).Table(d.tableName(userId)).Where("user_id = ? and send_time = ?", userId, sendTime).
  70. Update("status", status)
  71. if db.Error != nil {
  72. return 0, gerrors.WrapError(db.Error)
  73. }
  74. return db.RowsAffected, nil
  75. }