roese-utils/rspagination/rspagination.go

77 lines
1.9 KiB
Go
Raw Normal View History

2023-10-13 08:49:38 +02:00
package rspagination
import (
"math"
"gorm.io/gorm"
)
// GetTotalPages returns total pages for pagination
// Example whereQuery = "stock_item_id = ?" and args = stockItemId is Where("stock_item_id = ?", stockItemId)
func GetTotalPages(database *gorm.DB, paginationLimit int, any interface{}, whereQuery interface{}, args ...interface{}) int {
var totalPages int64
2023-10-13 15:41:38 +02:00
if whereQuery == nil {
database.Model(any).
Count(&totalPages)
2023-11-26 09:51:19 +01:00
} else if len(args) == 0 { // here used with db.Where(&User{Name: "jinzhu", Age: 20}).First(&user)
database.Model(any).
Where(whereQuery).
Count(&totalPages)
} else { // here used with "name = ?", "jinzhu"
2023-10-13 15:41:38 +02:00
database.Model(any).
Where(whereQuery, args).
Count(&totalPages)
}
2023-10-13 08:49:38 +02:00
2023-10-13 16:12:53 +02:00
return CalculateTotalPages(int(totalPages), paginationLimit)
}
func CalculateTotalPages(totalItems int, paginationLimit int) int {
return int(math.Ceil(float64(totalItems) / float64(paginationLimit)))
2023-10-13 08:49:38 +02:00
}
func GetPageOffset(page int, paginationLimit int) int {
return (page - 1) * paginationLimit
}
type PageQuery struct {
Page int
}
2023-11-26 00:12:53 +01:00
func DbPageQuery(database *gorm.DB, query PageQuery, paginationLimit int, result any, orderBy string, whereQuery interface{}, args ...interface{}) *gorm.DB {
2023-11-26 00:24:27 +01:00
if whereQuery == nil {
return database.Limit(paginationLimit).
Offset(GetPageOffset(query.Page, paginationLimit)).
Order(orderBy).
Find(result)
}
2023-10-13 16:11:02 +02:00
2023-11-26 00:12:53 +01:00
return database.Limit(paginationLimit).
Offset(GetPageOffset(query.Page, paginationLimit)).
2023-11-26 00:24:27 +01:00
Where(whereQuery, args).
2023-11-26 00:12:53 +01:00
Order(orderBy).
Find(result)
}
2023-10-13 16:11:02 +02:00
// GetPage returns start and end for pagination
// can be used like this: robots[start:end]
func GetPage(lenList int, page int, limit int) (start int, end int) {
if page <= 0 {
page = 1
}
start = (page - 1) * limit
end = page * limit
if start > lenList {
start = lenList
}
if end > lenList {
end = lenList
}
return start, end
}