Files
mtusi2026lab2/app/internal/common/paginator.go
T
2026-10-23 18:55:20 +03:00

109 lines
2.6 KiB
Go

package common
import (
"encoding/base64"
"strconv"
"strings"
"time"
"github.com/gofiber/fiber/v3"
"github.com/google/uuid"
)
// CursorKeyCtx is the opaque keyset position: (created_at, id) plus the
// resource/user the cursor belongs to. ContextID stops a cursor from one chat
// or user list being replayed against another.
type CursorKeyCtx struct {
Time time.Time
ID uuid.UUID
ContextID uuid.UUID
}
type Page[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 !exists {
return defaultLimit, nil
}
if strings.TrimSpace(limitStr) == "" {
return 0, BadRequest("limit param declared but empty")
}
limit, err := strconv.Atoi(limitStr)
if err != nil || limit < 1 || limit > 100 {
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 !exists {
return nil, nil
}
if strings.TrimSpace(cursorStr) == "" {
return nil, BadRequest("cursor param declared but empty")
}
cursor, ok := DecodeCursor(cursorStr)
if !ok {
return nil, BadRequest("invalid cursor format")
}
return cursor, nil
}
func EncodeCursor(key CursorKeyCtx) string {
raw := key.Time.UTC().Format(time.RFC3339Nano) + "|" + key.ID.String() + "|" + key.ContextID.String()
return base64.RawURLEncoding.EncodeToString([]byte(raw))
}
func DecodeCursor(cursor string) (*CursorKeyCtx, bool) {
data, err := base64.RawURLEncoding.DecodeString(cursor)
if err != nil {
return nil, false
}
parts := strings.SplitN(string(data), "|", 3)
if len(parts) != 3 {
return nil, false
}
parsedTime, err := time.Parse(time.RFC3339Nano, parts[0])
if err != nil {
return nil, false
}
parsedID, err := uuid.Parse(parts[1])
if err != nil {
return nil, false
}
parsedContext, err := uuid.Parse(parts[2])
if err != nil {
return nil, false
}
return &CursorKeyCtx{Time: parsedTime, ID: parsedID, ContextID: parsedContext}, true
}
// NextCursor returns a cursor pointing at the last item of a page when more
// rows exist. limit+1 rows are fetched by the store, so a non-nil cursor means
// the next page is known to be non-empty at read time.
func NextCursor[T interface {
GetID() uuid.UUID
GetCreatedAt() time.Time
}](items []T, hasMore bool, contextID uuid.UUID) *string {
if !hasMore || len(items) == 0 {
return nil
}
last := items[len(items)-1]
encoded := EncodeCursor(CursorKeyCtx{
Time: last.GetCreatedAt(),
ID: last.GetID(),
ContextID: contextID,
})
return &encoded
}