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.

111 lines
1.8 KiB

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