helpers.go 809 B

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. package helpers
  2. import (
  3. "math"
  4. "gorm.io/gorm"
  5. )
  6. type PaginatedResult struct {
  7. NumPages int64
  8. CurrentPage int64
  9. NextPage int64 `json:"next_page,omitempty"`
  10. }
  11. func Paginate(db *gorm.DB, pagination *PaginatedResult, opts ...QueryOption) func(db *gorm.DB) *gorm.DB {
  12. q := Query{
  13. PageSize: 50,
  14. Page: 0,
  15. }
  16. for _, opt := range opts {
  17. opt(&q)
  18. }
  19. var totalRows int64
  20. db.Count(&totalRows)
  21. offset := (q.Page - 1) * q.PageSize
  22. pagination.NumPages = int64(math.Ceil(float64(totalRows) / float64(q.PageSize)))
  23. pagination.CurrentPage = int64(q.Page)
  24. pagination.NextPage = int64(q.Page + 1)
  25. if pagination.CurrentPage >= pagination.NumPages {
  26. pagination.NextPage = pagination.NumPages
  27. }
  28. return func(db *gorm.DB) *gorm.DB {
  29. return db.
  30. Offset(offset).
  31. Limit(q.PageSize)
  32. }
  33. }