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.

78 lines
1.3 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 GetFrontPagePosts() ([]Models.Post, error) {
  9. var (
  10. posts []Models.Post
  11. err error
  12. )
  13. err = DB.Where("front_page = ?", true).
  14. Where("published_at IS NOT NULL").
  15. Order("order asc").
  16. Find(&posts).
  17. Error
  18. return posts, err
  19. }
  20. func GetPostsPublic(page, pageSize int, search string) ([]Models.Post, error) {
  21. var (
  22. posts []Models.Post
  23. query *gorm.DB
  24. offset int
  25. err error
  26. )
  27. switch {
  28. case pageSize > 100:
  29. pageSize = 100
  30. case pageSize <= 0:
  31. pageSize = 10
  32. }
  33. offset = page * pageSize
  34. search = fmt.Sprintf("%%%s%%", search)
  35. query = DB.Model(Models.Post{}).
  36. Preload(clause.Associations).
  37. Where("published_at IS NOT NULL").
  38. Offset(offset).
  39. Limit(pageSize).
  40. Order("created_at desc")
  41. if search != "%%" {
  42. query = query.
  43. Where("title LIKE ?", search).
  44. Or("content LIKE ?", search)
  45. }
  46. err = query.
  47. Find(&posts).
  48. Error
  49. return posts, err
  50. }
  51. func GetPostByIdPublic(id string) (Models.Post, error) {
  52. var (
  53. postData Models.Post
  54. err error
  55. )
  56. err = DB.Preload(clause.Associations).
  57. Where("published_at IS NOT NULL").
  58. First(&postData, "id = ?", id).
  59. Error
  60. return postData, err
  61. }