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.

114 lines
1.6 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 GetUsers(page, pageSize int) ([]Models.User, error) {
  20. var (
  21. users []Models.User
  22. i int
  23. err error
  24. )
  25. if page == 0 {
  26. page = 1
  27. }
  28. switch {
  29. case pageSize > 100:
  30. pageSize = 100
  31. case pageSize <= 0:
  32. pageSize = 10
  33. }
  34. err = DB.Offset(page).
  35. Limit(pageSize).
  36. Find(&users).
  37. Error
  38. for i, _ = range users {
  39. users[i].Password = ""
  40. }
  41. return users, err
  42. }
  43. func CheckUniqueEmail(email string) error {
  44. var (
  45. exists bool
  46. err error
  47. )
  48. err = DB.Model(Models.User{}).
  49. Select("count(*) > 0").
  50. Where("email = ?", email).
  51. Find(&exists).
  52. Error
  53. if err != nil {
  54. return err
  55. }
  56. if exists {
  57. return errors.New("Invalid email")
  58. }
  59. return nil
  60. }
  61. func CreateUser(userData *Models.User) error {
  62. var (
  63. err error
  64. )
  65. err = DB.Session(&gorm.Session{FullSaveAssociations: true}).
  66. Create(userData).
  67. Error
  68. userData.Password = ""
  69. return err
  70. }
  71. func UpdateUser(id string, userData *Models.User) error {
  72. var (
  73. err error
  74. )
  75. err = DB.Model(&Models.Post{}).
  76. Select("*").
  77. Omit("id", "created_at", "updated_at", "deleted_at").
  78. Where("id = ?", id).
  79. Updates(userData).
  80. Error
  81. userData.Password = ""
  82. return err
  83. }
  84. func DeleteUser(userData *Models.User) error {
  85. return DB.Session(&gorm.Session{FullSaveAssociations: true}).
  86. Delete(userData).
  87. Error
  88. }