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.

message_repo.go 1.8 KiB

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