
Security News
Vite Releases Technical Preview of Rolldown-Vite, a Rust-Based Bundler
Vite releases Rolldown-Vite, a Rust-based bundler preview offering faster builds and lower memory usage as a drop-in replacement for Vite.
github.com/pilagod/gorm-cursor-paginator
A paginator doing cursor-based pagination based on GORM
go get -u github.com/pilagod/gorm-cursor-paginator
For more comprehensive examples, you can check example/main.go and paginator_test.go
Assume there is an query struct for paging:
type PagingQuery struct {
After *string
Before *string
Limit *int
Order *string
}
and a GORM model:
type Model struct {
ID int
CreatedAt time.Time
}
You can simply build up a new cursor paginator from the PagingQuery like:
import (
paginator "github.com/pilagod/gorm-cursor-paginator"
)
func GetModelPaginator(q PagingQuery) *paginator.Paginator {
p := paginator.New()
p.SetKeys("CreatedAt", "ID") // [default: "ID"] (supporting multiple keys, order of keys matters)
if q.After != nil {
p.SetAfterCursor(*q.After) // [default: nil]
}
if q.Before != nil {
p.SetBeforeCursor(*q.Before) // [default: nil]
}
if q.Limit != nil {
p.SetLimit(*q.Limit) // [default: 10]
}
if q.Order != nil && *q.Order == "asc" {
p.SetOrder(paginator.ASC) // [default: paginator.DESC]
}
return p
}
Then you can start to do pagination easily with GORM:
func Find(db *gorm.DB, q PagingQuery) ([]Model, paginator.Cursor, error) {
var models []Model
stmt := db.Where(/* ... other filters ... */)
stmt = db.Or(/* ... more other filters ... */)
// get paginator for Model
p := GetModelPaginator(q)
// use GORM-like syntax to do pagination
result := p.Paginate(stmt, &models)
if result.Error != nil {
// ...
}
// get cursor for next iteration
cursor := p.GetNextCursor()
return models, cursor, nil
}
After paginating, you can call GetNextCursor()
, which returns a Cursor
struct containing cursor for next iteration:
type Cursor struct {
After *string `json:"after"`
Before *string `json:"before"`
}
That's all ! Enjoy your paging in the GORM world :tada:
© Chun-Yan Ho (pilagod), 2018-NOW
Released under the MIT License
FAQs
Unknown package
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Vite releases Rolldown-Vite, a Rust-based bundler preview offering faster builds and lower memory usage as a drop-in replacement for Vite.
Research
Security News
A malicious npm typosquat uses remote commands to silently delete entire project directories after a single mistyped install.
Research
Security News
Malicious PyPI package semantic-types steals Solana private keys via transitive dependency installs using monkey patching and blockchain exfiltration.