pilagod / gorm-cursor-paginator

A paginator doing cursor-based pagination based on GORM
https://github.com/pilagod/gorm-cursor-paginator
MIT License
188 stars 44 forks source link

[question] Cursor of each row #20

Closed theomjones closed 3 years ago

theomjones commented 4 years ago

Is there a way to get the cursor for each row without manually encoding the key value?

pilagod commented 3 years ago

Hello @theomjones, sorry for the late reply 😢

In this module there are public cursor encoder and decoder utils can be leveraged, which are not documented in README right now.

You can refer to cursor_test.go#L184 and cursor_test.go#L222 to see how to create and use cursor encoder and decoder. Test cases in cursor_test.go show more details for how encoder and decoder work.

Also provide an example here:

import (
    paginator "github.com/pilagod/gorm-cursor-paginator"
)

type Model struct {
    ID string
}

// Encode returns cursor made by specified field values from Model
func (m *Model) Encode() string {
    encoder := paginator.NewCursorEncoder([]string{"ID"})
    return encoder.Encode(m)
}

// Decode []interface{} returned contains specified field values from Model in order
func (m *Model) Decode(cursor string) ([]interface{}, error) {
    decoder, err := paginator. NewCursorDecoder(m, []string{"ID"})
    if err != nil {
        return nil, err
    }
    return decoder.Decode(cursor), nil
}

func main() {
    m := Model{ID: "ModelID"}
    cursor := m.Encode()
    fields, _ := m.Decode(cursor)
    fmt.Println(fields[0]) // which would be "ModelID"
}