common/structs/storage/scope.go

55 lines
918 B
Go

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
}
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
}
func (p *PageListQuery) Scope(db *gorm.DB) *gorm.DB {
if p.Scoper != nil {
db = p.Scoper.Scope(db)
}
return p.PageQuery.Scope(db)
}