gorm-cursor-paginator

A paginator doing cursor-based pagination based on GORM

Github星跟蹤圖

gorm-cursor-paginator
Build Status
Coverage Status
Go Report Card
Codacy Badge

A paginator doing cursor-based pagination based on GORM

Installation

go get -u github.com/pilagod/gorm-cursor-paginator

Usage by Example

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:

License

© Chun-Yan Ho (pilagod), 2018-NOW

Released under the MIT License

主要指標

概覽
名稱與所有者pilagod/gorm-cursor-paginator
主編程語言Go
編程語言Go (語言數: 2)
平台
許可證MIT License
所有者活动
創建於2018-10-09 10:09:20
推送於2025-05-23 07:39:46
最后一次提交2025-05-23 16:37:17
發布數21
最新版本名稱v2.7.0 (發布於 2025-05-23 15:37:55)
第一版名稱v0.1.0 (發布於 2018-10-14 01:23:34)
用户参与
星數205
關注者數5
派生數44
提交數194
已啟用問題?
問題數31
打開的問題數1
拉請求數38
打開的拉請求數1
關閉的拉請求數1
项目设置
已啟用Wiki?
已存檔?
是復刻?
已鎖定?
是鏡像?
是私有?