docs: add godoc comments to public functions and types
This commit is contained in:
@@ -1,3 +1,5 @@
|
||||
// Package pagination provides cursor-based pagination utilities for GraphQL Relay-style pagination.
|
||||
// Cursors are base64-encoded strings that can be used with first/after and last/before parameters.
|
||||
package pagination
|
||||
|
||||
import (
|
||||
@@ -6,6 +8,7 @@ import (
|
||||
"slices"
|
||||
)
|
||||
|
||||
// Pagination validation errors.
|
||||
var (
|
||||
ErrFirstAndLastProvided = errors.New("only one of first and last can be provided")
|
||||
ErrFirstNegative = errors.New("first must be greater than 0")
|
||||
@@ -16,6 +19,9 @@ var (
|
||||
ErrInvalidCursor = errors.New("invalid cursor")
|
||||
)
|
||||
|
||||
// Validate checks that the pagination parameters are valid according to Relay specification.
|
||||
// It ensures that first and last are not both provided, that they are non-negative,
|
||||
// and that after and before cursors are valid base64-encoded strings.
|
||||
func Validate(first *int, after *string, last *int, before *string) error {
|
||||
if first != nil && last != nil {
|
||||
return ErrFirstAndLastProvided
|
||||
@@ -38,6 +44,8 @@ func Validate(first *int, after *string, last *int, before *string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// ValidateCursor checks if a cursor is a valid base64-encoded string.
|
||||
// Returns nil if the cursor is nil or valid, ErrInvalidCursor otherwise.
|
||||
func ValidateCursor(cursor *string) error {
|
||||
_, err := DecodeCursor(cursor)
|
||||
if err != nil {
|
||||
@@ -46,6 +54,8 @@ func ValidateCursor(cursor *string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// DecodeCursor decodes a base64-encoded cursor string.
|
||||
// Returns an empty string if the cursor is nil.
|
||||
func DecodeCursor(cursor *string) (string, error) {
|
||||
if cursor == nil {
|
||||
return "", nil
|
||||
@@ -57,10 +67,14 @@ func DecodeCursor(cursor *string) (string, error) {
|
||||
return string(b64), nil
|
||||
}
|
||||
|
||||
// EncodeCursor encodes a string value as a base64 cursor.
|
||||
func EncodeCursor(cursor string) string {
|
||||
return base64.StdEncoding.EncodeToString([]byte(cursor))
|
||||
}
|
||||
|
||||
// GetPage returns a paginated slice of items based on the provided pagination parameters.
|
||||
// The fn parameter extracts the cursor value from each item.
|
||||
// If neither first nor last is provided, max is used as the default page size.
|
||||
func GetPage[T any](items []T, first *int, after *string, last *int, before *string, max int, fn func(T) string) ([]T, PageInfo) {
|
||||
if len(items) == 0 {
|
||||
return nil, PageInfo{}
|
||||
@@ -117,6 +131,7 @@ func ptr[T any](v T) *T {
|
||||
return &v
|
||||
}
|
||||
|
||||
// PageInfo contains pagination metadata for a page of results.
|
||||
type PageInfo struct {
|
||||
StartCursor *string
|
||||
HasNextPage bool
|
||||
|
||||
Reference in New Issue
Block a user