Files
mtusi2026lab2/app/internal/common/paginator.go
T

199 lines
3.5 KiB
Go

package common
import (
"encoding/base64"
"sort"
"strings"
"time"
"github.com/gofiber/fiber/v3"
"github.com/google/uuid"
)
type CursorKeyCtx struct {
Time time.Time
ID uuid.UUID
ContextID uuid.UUID
}
type cursorKey struct {
time time.Time
id uuid.UUID
}
type CreatedAtIDable interface {
GetCreatedAt() time.Time
GetID() uuid.UUID
}
type PaginatedResponse[T any] struct {
Items []T `json:"items"`
NextCursor *string `json:"next_cursor"`
}
func ParseLimit(c fiber.Ctx, defaultLimit int) (int, error) {
limitStr, exists := c.Queries()["limit"]
if limitStr == "" {
if !exists {
return defaultLimit, nil
}
return 0, BadRequest("limit param declared but empty")
}
limit, ok := validateLimitStr(limitStr)
if !ok {
return 0, BadRequest("limit must be an integer between 1 and 100")
}
return limit, nil
}
func ParseCursor(c fiber.Ctx) (*CursorKeyCtx, error) {
cursorStr, exists := c.Queries()["cursor"]
if cursorStr == "" {
if !exists {
return nil, nil
}
return nil, BadRequest("cursor param declared but empty")
}
cursor := DecodeCursor(cursorStr)
if cursor == nil {
return nil, BadRequest("invalid cursor format")
}
return cursor, nil
}
func Paginate[T CreatedAtIDable](
items []T,
limit int,
cursor *CursorKeyCtx,
contextID uuid.UUID,
) (*PaginatedResponse[T], error) {
enforceOrder(items)
start := 0
if cursor != nil {
key := cursorKey{time: cursor.Time, id: cursor.ID}
position, found := findAfter(items, key)
if !found {
return nil, BadRequest("cursor invalid")
}
if position == -1 {
position = len(items)
}
start = position
}
end := start + limit
if end > len(items) {
end = len(items)
}
page := items[start:end]
if page == nil {
page = []T{}
}
var nextCursor *string
if end < len(items) {
last := items[end-1]
encoded := encodeCursor(CursorKeyCtx{
Time: last.GetCreatedAt(),
ID: last.GetID(),
ContextID: contextID,
})
nextCursor = &encoded
}
return &PaginatedResponse[T]{
Items: page,
NextCursor: nextCursor,
}, nil
}
func encodeCursor(key CursorKeyCtx) string {
timeStr := key.Time.UTC().Format(time.RFC3339Nano)
raw := timeStr + "|" + key.ID.String() + "|" + key.ContextID.String()
return base64.RawURLEncoding.EncodeToString([]byte(raw))
}
func DecodeCursor(cursor string) *CursorKeyCtx {
data, err := base64.RawURLEncoding.DecodeString(cursor)
if err != nil {
return nil
}
parts := strings.SplitN(string(data), "|", 3)
if len(parts) != 3 {
return nil
}
parsedTime, err := time.Parse(time.RFC3339Nano, parts[0])
if err != nil {
return nil
}
parsedID, err := uuid.Parse(parts[1])
if err != nil {
return nil
}
parsedContextID, err := uuid.Parse(parts[2])
if err != nil {
return nil
}
return &CursorKeyCtx{
Time: parsedTime,
ID: parsedID,
ContextID: parsedContextID,
}
}
func findAfter[T CreatedAtIDable](items []T, key cursorKey) (position int, keyFound bool) {
for i, item := range items {
itemKey := keyOf(item)
if itemKey == key {
keyFound = true
}
if after(itemKey, key) {
return i, true
}
}
return -1, keyFound
}
func keyOf(item CreatedAtIDable) cursorKey {
return cursorKey{
time: item.GetCreatedAt(),
id: item.GetID(),
}
}
func after(a, b cursorKey) bool {
if !a.time.Equal(b.time) {
return a.time.After(b.time)
}
return a.id.String() > b.id.String()
}
func enforceOrder[T CreatedAtIDable](items []T) {
sort.Slice(items, func(i, j int) bool {
return after(keyOf(items[j]), keyOf(items[i]))
})
}