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.

127 lines
1.9 KiB

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