forked from mtusi2026/mtusi2026lab4
48 lines
1.3 KiB
Go
48 lines
1.3 KiB
Go
// Package cursor implements the opaque keyset cursor used by paged collections.
|
|
package cursor
|
|
|
|
import (
|
|
"encoding/base64"
|
|
"errors"
|
|
"strings"
|
|
"time"
|
|
|
|
"mtusi2026lab3/internal/domain"
|
|
"mtusi2026lab3/internal/validate"
|
|
)
|
|
|
|
// ErrInvalid marks a cursor that cannot be decoded or belongs to another resource.
|
|
var ErrInvalid = errors.New("invalid cursor")
|
|
|
|
// Value is a decoded (created_at, id) position bound to one collection scope.
|
|
type Value struct {
|
|
CreatedAt time.Time
|
|
ID string
|
|
}
|
|
|
|
// Encode serialises a position so clients can replay it but not forge a new one.
|
|
func Encode(scope string, createdAt time.Time, id string) string {
|
|
raw := scope + "|" + createdAt.UTC().Format(domain.TimeFormat) + "|" + id
|
|
return base64.RawURLEncoding.EncodeToString([]byte(raw))
|
|
}
|
|
|
|
// Decode validates the cursor and rejects one issued for another collection.
|
|
func Decode(encoded, scope string) (Value, error) {
|
|
raw, err := base64.RawURLEncoding.DecodeString(encoded)
|
|
if err != nil {
|
|
return Value{}, ErrInvalid
|
|
}
|
|
parts := strings.Split(string(raw), "|")
|
|
if len(parts) != 3 || parts[0] != scope {
|
|
return Value{}, ErrInvalid
|
|
}
|
|
createdAt, err := time.Parse(domain.TimeFormat, parts[1])
|
|
if err != nil {
|
|
return Value{}, ErrInvalid
|
|
}
|
|
if !validate.UUID(parts[2]) {
|
|
return Value{}, ErrInvalid
|
|
}
|
|
return Value{CreatedAt: createdAt.UTC(), ID: parts[2]}, nil
|
|
}
|