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.

96 lines
1.5 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. DB.Model(postData).
  58. Where("id = ?", id).
  59. Association("PostLinks").
  60. Replace(postData.PostLinks)
  61. err = DB.Model(&Models.Post{}).
  62. Select("*").
  63. Omit("id", "created_at", "updated_at", "deleted_at").
  64. Where("id = ?", id).
  65. Updates(postData).
  66. Error
  67. if err != nil {
  68. return Models.Post{}, err
  69. }
  70. return GetPostById(id)
  71. }
  72. func DeletePost(postData *Models.Post) error {
  73. return DB.Session(&gorm.Session{FullSaveAssociations: true}).
  74. Delete(postData).
  75. Error
  76. }