commit bb957c802752fd2cae3cfb4324d573653ddc9a6f Author: ivamp Date: Sat May 18 00:12:01 2024 +0800 init diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..a09c56d --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +/.idea diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..7ae6090 --- /dev/null +++ b/go.mod @@ -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 +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..69cab05 --- /dev/null +++ b/go.sum @@ -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= diff --git a/paginate.go b/paginate.go new file mode 100644 index 0000000..4e30c44 --- /dev/null +++ b/paginate.go @@ -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) + } +}