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.

90 lines
1.4 KiB

  1. package Database
  2. import (
  3. "git.tovijaeschke.xyz/tovi/SuddenImpactRecords/Models"
  4. "gorm.io/gorm"
  5. "gorm.io/gorm/clause"
  6. )
  7. func GetPosts(page, pageSize int) ([]Models.Post, error) {
  8. var (
  9. posts []Models.Post
  10. err error
  11. )
  12. if page == 0 {
  13. page = 1
  14. }
  15. switch {
  16. case pageSize > 100:
  17. pageSize = 100
  18. case pageSize <= 0:
  19. pageSize = 10
  20. }
  21. err = DB.Offset(page).
  22. Limit(pageSize).
  23. Find(&posts).
  24. Error
  25. return posts, err
  26. }
  27. func GetFrontPagePosts() ([]Models.Post, error) {
  28. var (
  29. posts []Models.Post
  30. err error
  31. )
  32. err = DB.Where("front_page = ?", true).
  33. Order("order asc").
  34. Find(&posts).
  35. Error
  36. return posts, err
  37. }
  38. func GetPostById(id string) (Models.Post, error) {
  39. var (
  40. postData Models.Post
  41. err error
  42. )
  43. err = DB.Preload(clause.Associations).
  44. First(&postData, "id = ?", id).
  45. Error
  46. return postData, err
  47. }
  48. func CreatePost(postData *Models.Post) error {
  49. return DB.Session(&gorm.Session{FullSaveAssociations: true}).
  50. Create(postData).
  51. Error
  52. }
  53. func UpdatePost(id string, postData *Models.Post) (Models.Post, error) {
  54. var (
  55. err error
  56. )
  57. err = DB.Model(&Models.Post{}).
  58. Select("*").
  59. Omit("id", "created_at", "updated_at", "deleted_at").
  60. Where("id = ?", id).
  61. Updates(postData).
  62. Error
  63. if err != nil {
  64. return Models.Post{}, err
  65. }
  66. return GetPostById(id)
  67. }
  68. func DeletePost(postData *Models.Post) error {
  69. return DB.Session(&gorm.Session{FullSaveAssociations: true}).
  70. Delete(postData).
  71. Error
  72. }