86 lines
2.1 KiB
Go
86 lines
2.1 KiB
Go
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
|
|
|
|
if whereQuery == nil {
|
|
database.Model(any).
|
|
Count(&totalPages)
|
|
} 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"
|
|
database.Model(any).
|
|
Where(whereQuery, args).
|
|
Count(&totalPages)
|
|
}
|
|
|
|
return CalculateTotalPages(int(totalPages), paginationLimit)
|
|
}
|
|
|
|
func CalculateTotalPages(totalItems int, paginationLimit int) int {
|
|
return int(math.Ceil(float64(totalItems) / float64(paginationLimit)))
|
|
}
|
|
|
|
func GetPageOffset(page int, paginationLimit int) int {
|
|
return (page - 1) * paginationLimit
|
|
}
|
|
|
|
type PageQuery struct {
|
|
Page int
|
|
}
|
|
|
|
func DbPageQuery(database *gorm.DB, query PageQuery, paginationLimit int, result any, orderBy string, whereQuery interface{}, args ...interface{}) *gorm.DB {
|
|
if whereQuery == nil {
|
|
return database.Limit(paginationLimit).
|
|
Offset(GetPageOffset(query.Page, paginationLimit)).
|
|
Order(orderBy).
|
|
Find(result)
|
|
}
|
|
|
|
if len(args) == 0 { // here used with db.Where(&User{Name: "jinzhu", Age: 20}).First(&user)
|
|
return database.Limit(paginationLimit).
|
|
Offset(GetPageOffset(query.Page, paginationLimit)).
|
|
Where(whereQuery).
|
|
Order(orderBy).
|
|
Find(result)
|
|
}
|
|
|
|
// here used with "name = ?", "jinzhu"
|
|
return database.Limit(paginationLimit).
|
|
Offset(GetPageOffset(query.Page, paginationLimit)).
|
|
Where(whereQuery, args).
|
|
Order(orderBy).
|
|
Find(result)
|
|
}
|
|
|
|
// 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
|
|
}
|