优化结构
This commit is contained in:
@@ -0,0 +1,37 @@
|
||||
// Package pagination contains GORM pagination helpers shared by repository
|
||||
// implementations in the data layer.
|
||||
package pagination
|
||||
|
||||
import "gorm.io/gorm"
|
||||
|
||||
// LimitOffset normalizes a page request and applies the optional maximum page
|
||||
// size. A non-positive size means that no limit should be applied.
|
||||
func LimitOffset(page, size, maxSize int) (limit, offset int) {
|
||||
limit = size
|
||||
if maxSize > 0 && size > maxSize {
|
||||
limit = maxSize
|
||||
}
|
||||
if limit <= 0 {
|
||||
return 0, 0
|
||||
}
|
||||
if page <= 0 {
|
||||
page = 1
|
||||
}
|
||||
return limit, (page - 1) * limit
|
||||
}
|
||||
|
||||
// Apply applies pagination only when the caller supplied a positive size.
|
||||
func Apply(db *gorm.DB, page, size, maxSize int) *gorm.DB {
|
||||
limit, offset := LimitOffset(page, size, maxSize)
|
||||
if limit == 0 {
|
||||
return db
|
||||
}
|
||||
return db.Offset(offset).Limit(limit)
|
||||
}
|
||||
|
||||
// ApplyRequired always applies LIMIT/OFFSET, including LIMIT 0. This keeps
|
||||
// the existing repository contract for APIs whose page size is mandatory.
|
||||
func ApplyRequired(db *gorm.DB, page, size, maxSize int) *gorm.DB {
|
||||
limit, offset := LimitOffset(page, size, maxSize)
|
||||
return db.Offset(offset).Limit(limit)
|
||||
}
|
||||
Reference in New Issue
Block a user