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.

124 lines
1.8 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. switch {
  36. case pageSize > 100:
  37. pageSize = 100
  38. case pageSize <= 0:
  39. pageSize = 10
  40. }
  41. err = DB.Model(Models.User{}).
  42. Offset(0).
  43. Limit(10).
  44. Find(&users).
  45. Error
  46. for i, _ = range users {
  47. users[i].Password = ""
  48. }
  49. return users, err
  50. }
  51. func CheckUniqueEmail(email string) error {
  52. var (
  53. exists bool
  54. err error
  55. )
  56. err = DB.Model(Models.User{}).
  57. Select("count(*) > 0").
  58. Where("email = ?", email).
  59. Find(&exists).
  60. Error
  61. if err != nil {
  62. return err
  63. }
  64. if exists {
  65. return errors.New("Invalid email")
  66. }
  67. return nil
  68. }
  69. func CreateUser(userData *Models.User) error {
  70. var (
  71. err error
  72. )
  73. err = DB.Session(&gorm.Session{FullSaveAssociations: true}).
  74. Create(userData).
  75. Error
  76. userData.Password = ""
  77. return err
  78. }
  79. func UpdateUser(id string, userData *Models.User) error {
  80. var (
  81. err error
  82. )
  83. err = DB.Model(&Models.User{}).
  84. Select("*").
  85. Omit("id", "created_at", "updated_at", "deleted_at").
  86. Where("id = ?", id).
  87. Updates(userData).
  88. Error
  89. userData.Password = ""
  90. return err
  91. }
  92. func DeleteUser(userData *Models.User) error {
  93. return DB.Session(&gorm.Session{FullSaveAssociations: true}).
  94. Delete(userData).
  95. Error
  96. }