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.

97 lines
1.6 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 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. }