99 lines
1.8 KiB
Go
99 lines
1.8 KiB
Go
package service
|
|
|
|
import (
|
|
"encoding/base64"
|
|
"encoding/json"
|
|
"sort"
|
|
"time"
|
|
)
|
|
|
|
type Page[T any] struct {
|
|
Items []T `json:"items"`
|
|
NextCursor *string `json:"next_cursor"`
|
|
}
|
|
|
|
type position struct {
|
|
CreatedAt time.Time `json:"created_at"`
|
|
ID string `json:"id"`
|
|
}
|
|
|
|
type cursorData struct {
|
|
Scope string `json:"scope"`
|
|
After position `json:"after"`
|
|
}
|
|
|
|
func less(a, b position) bool {
|
|
if a.CreatedAt.Equal(b.CreatedAt) {
|
|
return a.ID < b.ID
|
|
}
|
|
return a.CreatedAt.Before(b.CreatedAt)
|
|
}
|
|
|
|
func paginate[T any](
|
|
items []T,
|
|
scope string,
|
|
limit int,
|
|
cursor string,
|
|
key func(T) position,
|
|
) (Page[T], error) {
|
|
if limit < 1 || limit > 100 {
|
|
return Page[T]{}, ErrInvalidRequest
|
|
}
|
|
|
|
var after *position
|
|
|
|
if cursor != "" {
|
|
raw, err := base64.RawURLEncoding.DecodeString(cursor)
|
|
if err != nil {
|
|
return Page[T]{}, ErrInvalidRequest
|
|
}
|
|
|
|
var decoded cursorData
|
|
if err := json.Unmarshal(raw, &decoded); err != nil {
|
|
return Page[T]{}, ErrInvalidRequest
|
|
}
|
|
|
|
if decoded.Scope != scope ||
|
|
decoded.After.CreatedAt.IsZero() ||
|
|
!uuidPattern.MatchString(decoded.After.ID) {
|
|
return Page[T]{}, ErrInvalidRequest
|
|
}
|
|
|
|
after = &decoded.After
|
|
}
|
|
|
|
sort.Slice(items, func(i, j int) bool {
|
|
return less(key(items[i]), key(items[j]))
|
|
})
|
|
|
|
start := 0
|
|
|
|
if after != nil {
|
|
start = sort.Search(len(items), func(i int) bool {
|
|
return less(*after, key(items[i]))
|
|
})
|
|
}
|
|
|
|
end := min(start+limit, len(items))
|
|
|
|
page := Page[T]{
|
|
Items: make([]T, end-start),
|
|
}
|
|
copy(page.Items, items[start:end])
|
|
|
|
if end < len(items) {
|
|
raw, err := json.Marshal(cursorData{
|
|
Scope: scope,
|
|
After: key(items[end-1]),
|
|
})
|
|
if err != nil {
|
|
return Page[T]{}, err
|
|
}
|
|
|
|
next := base64.RawURLEncoding.EncodeToString(raw)
|
|
page.NextCursor = &next
|
|
}
|
|
|
|
return page, nil
|
|
}
|