package paginate
import (
"math"
"gorm.io/gorm"
)
// Param 分页参数
type Param struct {
DB *gorm.DB
PageNo int
PageSize int
OrderBy []string
ShowSQL bool
}
// Paginator 分页返回
type Paginator struct {
TotalCount int64 `json:"total_count"`
TotalPage int `json:"total_page"`
Records interface{} `json:"records"`
Current int `json:"current"`
PageSize int `json:"page_size"`
}
// Paging 分页
func Paging[T any](p *Param, result *T) *Paginator {
db := p.DB
if p.ShowSQL {
db = db.Debug()
}
if p.PageNo < 1 {
p.PageNo = 1
}
if p.PageSize == 0 {
p.PageSize = 10
}
done := make(chan bool, 1)
var paginator Paginator
var count int64
var offset int
go countRecords(db, result, done, &count)
if p.PageNo == 1 {
offset = 0
} else {
offset = (p.PageNo - 1) * p.PageSize
}
if len(p.OrderBy) > 0 {
for _, o := range p.OrderBy {
db = db.Order(o)
}
}
db.Limit(p.PageSize).Offset(offset).Find(result)
<-done
paginator.TotalCount = count
paginator.Records = result
paginator.Current = p.PageNo
paginator.PageSize = p.PageSize
paginator.TotalPage = int(math.Ceil(float64(count) / float64(p.PageSize)))
return &paginator
}
func countRecords(db *gorm.DB, anyType interface{}, done chan bool, count *int64) {
db.Count(count)
done <- true
}
func (l *GetRoleListLogic) GetRoleList(req *types.RoleReq) (resp *types.Pagina[types.RoleRes], err error) {
records := []types.RoleRes{}
pack := paginate.Paging[[]types.RoleRes](&paginate.Param{
DB: l.svcCtx.Gorm.Table("sys_role").Where(req),
PageNo: req.PageNo,
PageSize: req.PageSize,
OrderBy: []string{"create_time DESC"},
ShowSQL: true,
}, &records)
return &types.Pagina[types.RoleRes]{
TotalCount: pack.TotalCount,
TotalPage: pack.Current,
Records: records,
Current: pack.Current,
PageSize: pack.PageSize,
}, nil
}
接受一个泛型,泛型为返回的数组对象,用于保存查询出来的结果