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.

148 lines
2.2 KiB

  1. package Database
  2. import (
  3. "errors"
  4. "fmt"
  5. "git.tovijaeschke.xyz/tovi/SuddenImpactRecords/Models"
  6. "gorm.io/gorm"
  7. "gorm.io/gorm/clause"
  8. )
  9. func GetUserById(id string) (Models.User, error) {
  10. var (
  11. userData Models.User
  12. err error
  13. )
  14. err = DB.Preload(clause.Associations).
  15. First(&userData, "id = ?", id).
  16. Error
  17. userData.Password = ""
  18. return userData, err
  19. }
  20. func GetUserByEmail(email string) (Models.User, error) {
  21. var (
  22. userData Models.User
  23. err error
  24. )
  25. err = DB.Preload(clause.Associations).
  26. First(&userData, "email = ?", email).
  27. Error
  28. return userData, err
  29. }
  30. func GetUsers(page, pageSize int, search string) ([]Models.User, error) {
  31. var (
  32. users []Models.User
  33. query *gorm.DB
  34. offset int
  35. i int
  36. err error
  37. )
  38. switch {
  39. case pageSize > 100:
  40. pageSize = 100
  41. case pageSize <= 0:
  42. pageSize = 10
  43. }
  44. offset = page * pageSize
  45. search = fmt.Sprintf("%%%s%%", search)
  46. query = DB.Model(Models.User{}).
  47. Offset(offset).
  48. Limit(pageSize).
  49. Order("created_at desc")
  50. if search != "" {
  51. query = query.
  52. Where("CONCAT_WS(' ', first_name, last_name) LIKE ?", search).
  53. Or("email LIKE ?", search)
  54. }
  55. err = query.
  56. Find(&users).
  57. Error
  58. for i, _ = range users {
  59. users[i].Password = ""
  60. }
  61. return users, err
  62. }
  63. func CheckUniqueEmail(email string) error {
  64. var (
  65. exists bool
  66. err error
  67. )
  68. err = DB.Model(Models.User{}).
  69. Select("count(*) > 0").
  70. Where("email = ?", email).
  71. Find(&exists).
  72. Error
  73. if err != nil {
  74. return err
  75. }
  76. if exists {
  77. return errors.New("Invalid email")
  78. }
  79. return nil
  80. }
  81. func CreateUser(userData *Models.User) error {
  82. var (
  83. err error
  84. )
  85. err = DB.Session(&gorm.Session{FullSaveAssociations: true}).
  86. Create(userData).
  87. Error
  88. userData.Password = ""
  89. return err
  90. }
  91. func UpdateUser(id string, userData *Models.User) error {
  92. var (
  93. err error
  94. )
  95. err = DB.Model(&userData).
  96. Omit("id", "created_at", "updated_at", "deleted_at").
  97. Where("id = ?", id).
  98. Updates(userData).
  99. Error
  100. if err != nil {
  101. return err
  102. }
  103. err = DB.Model(Models.User{}).
  104. Where("id = ?", id).
  105. First(userData).
  106. Error
  107. userData.Password = ""
  108. return err
  109. }
  110. func DeleteUser(userData *Models.User) error {
  111. return DB.Session(&gorm.Session{FullSaveAssociations: true}).
  112. Delete(userData).
  113. Error
  114. }