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.
 
 
 
 

82 lines
2.0 KiB

  1. package repo
  2. import (
  3. "gim/internal/business/domain/user/model"
  4. "gim/pkg/db"
  5. "gim/pkg/gerrors"
  6. "time"
  7. "github.com/jinzhu/gorm"
  8. )
  9. type userDao struct{}
  10. var UserDao = new(userDao)
  11. // Add 插入一条用户信息
  12. func (*userDao) Add(user model.User) (int64, error) {
  13. user.CreateTime = time.Now()
  14. user.UpdateTime = time.Now()
  15. err := db.DB.Create(&user).Error
  16. if err != nil {
  17. return 0, gerrors.WrapError(err)
  18. }
  19. return user.Id, nil
  20. }
  21. // Get 获取用户信息
  22. func (*userDao) Get(userId int64) (*model.User, error) {
  23. var user = model.User{Id: userId}
  24. err := db.DB.First(&user).Error
  25. if err != nil && err != gorm.ErrRecordNotFound {
  26. return nil, gerrors.WrapError(err)
  27. }
  28. if err == gorm.ErrRecordNotFound {
  29. return nil, nil
  30. }
  31. return &user, err
  32. }
  33. // Save 保存
  34. func (*userDao) Save(user *model.User) error {
  35. err := db.DB.Save(user).Error
  36. if err != nil {
  37. return gerrors.WrapError(err)
  38. }
  39. return nil
  40. }
  41. // GetByPhoneNumber 根据手机号获取用户信息
  42. func (*userDao) GetByPhoneNumber(phoneNumber string, masterId int64) (*model.User, error) {
  43. var user model.User
  44. err := db.DB.First(&user, "phone_number = ? and master_id = ?", phoneNumber, masterId).Error
  45. if err != nil && err != gorm.ErrRecordNotFound {
  46. return nil, gerrors.WrapError(err)
  47. }
  48. if err == gorm.ErrRecordNotFound {
  49. return nil, nil
  50. }
  51. return &user, err
  52. }
  53. // GetByIds 获取用户信息
  54. func (*userDao) GetByIds(userIds []int64) ([]model.User, error) {
  55. var users []model.User
  56. err := db.DB.Find(&users, "id in (?)", userIds).Error
  57. if err != nil {
  58. return nil, gerrors.WrapError(err)
  59. }
  60. return users, err
  61. }
  62. // Search 查询用户,这里简单实现,生产环境建议使用ES
  63. func (*userDao) Search(key string, masterId int64) ([]model.User, error) {
  64. var users []model.User
  65. key = "%" + key + "%"
  66. err := db.DB.Where("phone_number like ? or nickname like ? and master_id = ?", key, key, masterId).Find(&users).Error
  67. if err != nil {
  68. return nil, gerrors.WrapError(err)
  69. }
  70. return users, nil
  71. }