This commit is contained in:
ivamp 2024-05-18 00:12:01 +08:00
commit bb957c8027
4 changed files with 80 additions and 0 deletions

1
.gitignore vendored Normal file
View File

@ -0,0 +1 @@
/.idea

10
go.mod Normal file
View File

@ -0,0 +1,10 @@
module leafdev.top/ivampiresp/helpers
go 1.22.3
require gorm.io/gorm v1.25.10
require (
github.com/jinzhu/inflection v1.0.0 // indirect
github.com/jinzhu/now v1.1.5 // indirect
)

6
go.sum Normal file
View File

@ -0,0 +1,6 @@
github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=
github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ=
github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
gorm.io/gorm v1.25.10 h1:dQpO+33KalOA+aFYGlK+EfxcI5MbO7EP2yYygwh9h+s=
gorm.io/gorm v1.25.10/go.mod h1:hbnx/Oo0ChWMn1BIhpy1oYozzpM15i4YPuHDmfYtwg8=

63
paginate.go Normal file
View File

@ -0,0 +1,63 @@
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)
}
}