common/structs/storage/scope.go

55 lines
918 B
Go
Raw Permalink Normal View History

2024-08-03 17:07:10 +08:00
package storage
import "gorm.io/gorm"
type Scoper interface {
Scope(db *gorm.DB) *gorm.DB
}
type PageQuery struct {
Page int `query:"page"`
Size int `query:"size"`
}
func (p *PageQuery) Scope(db *gorm.DB) *gorm.DB {
if p.Size <= 0 {
p.Size = 10
}
if p.Page <= 0 {
p.Page = 1
}
return db.Offset((p.Page - 1) * p.Size).Limit(p.Size)
}
type PageListQuery struct {
Scoper
PageQuery
}
2024-08-26 15:13:13 +08:00
func NewPageListQuery(scoper Scoper) *PageListQuery {
return &PageListQuery{Scoper: scoper}
}
func (p *PageListQuery) SetPage(page int) *PageListQuery {
p.Page = page
return p
}
func (p *PageListQuery) SetPageSize(pageSize int) *PageListQuery {
p.Size = pageSize
return p
}
func (p *PageListQuery) SetScoper(scoper Scoper) *PageListQuery {
p.Scoper = scoper
return p
}
2024-08-03 17:07:10 +08:00
func (p *PageListQuery) Scope(db *gorm.DB) *gorm.DB {
if p.Scoper != nil {
db = p.Scoper.Scope(db)
}
return p.PageQuery.Scope(db)
}