helpers/paginate.go

64 lines
1008 B
Go
Raw Normal View History

2024-05-17 16:12:01 +00:00
package helpers
import (
"gorm.io/gorm"
)
// Paginator 分页器
type Paginator[T any] struct {
Page int
Limit int
Count int64
Total int
Data []T
}
// NewPaginator 创建一个新的分页器实例
func NewPaginator[T any](tx *gorm.DB, page, limit int) (*Paginator[T], error) {
if page < 1 {
page = 1
}
// get T
beans := new([]T)
count := int64(0)
session := tx.Count(&count)
if session.Error != nil {
return nil, session.Error
}
paginator := &Paginator[T]{
Page: page,
Limit: limit,
Count: count,
Total: int((count + int64(limit) - 1) / int64(limit)),
}
// find
session = tx.Scopes(paginate(page, limit)).Find(&beans)
paginator.Data = *beans
return paginator, nil
}
func paginate(page int, limit int) func(db *gorm.DB) *gorm.DB {
return func(db *gorm.DB) *gorm.DB {
if page == 0 {
page = 1
}
switch {
case limit > 100:
limit = 100
case limit <= 0:
limit = 10
}
offset := (page - 1) * limit
return db.Offset(offset).Limit(limit)
}
}