forked from mtusi2026/mtusi2026lab2
56 lines
992 B
Go
56 lines
992 B
Go
package domain
|
|
|
|
import (
|
|
"encoding/base64"
|
|
"encoding/json"
|
|
"time"
|
|
)
|
|
|
|
type Page[T any] struct {
|
|
Items []T
|
|
NextCursor string
|
|
}
|
|
|
|
type Cursor struct {
|
|
CreatedAt time.Time `json:"t"`
|
|
ID string `json:"i"`
|
|
Scope string `json:"s,omitempty"`
|
|
}
|
|
|
|
func (c Cursor) IsZero() bool {
|
|
return c.ID == "" && c.CreatedAt.IsZero()
|
|
}
|
|
|
|
func (c Cursor) Less(createdAt time.Time, id string) bool {
|
|
if c.CreatedAt.Before(createdAt) {
|
|
return true
|
|
}
|
|
if c.CreatedAt.After(createdAt) {
|
|
return false
|
|
}
|
|
return c.ID < id
|
|
}
|
|
|
|
func EncodeCursor(c Cursor) string {
|
|
if c.IsZero() {
|
|
return ""
|
|
}
|
|
b, _ := json.Marshal(c)
|
|
return base64.RawURLEncoding.EncodeToString(b)
|
|
}
|
|
|
|
func DecodeCursor(s string) (Cursor, error) {
|
|
if s == "" {
|
|
return Cursor{}, nil
|
|
}
|
|
raw, err := base64.RawURLEncoding.DecodeString(s)
|
|
if err != nil {
|
|
return Cursor{}, ErrInvalidArgument
|
|
}
|
|
var c Cursor
|
|
if err := json.Unmarshal(raw, &c); err != nil {
|
|
return Cursor{}, ErrInvalidArgument
|
|
}
|
|
return c, nil
|
|
}
|