From bb3f7327cdf7bb2372e240940b3cabd0930fedb4 Mon Sep 17 00:00:00 2001 From: Joakim Olsson Date: Sun, 15 Jun 2025 19:56:47 +0200 Subject: [PATCH] fix(pagination): handle out-of-bounds slicing in pagination Ensure the pagination function correctly handles out-of-bounds indices when slicing items. Update the slice logic to prevent slice bounds errors and add a test case for better coverage of edge cases. --- pagination.go | 2 +- pagination_test.go | 10 ++++++++++ 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/pagination.go b/pagination.go index 36fd239..ada4e47 100644 --- a/pagination.go +++ b/pagination.go @@ -87,7 +87,7 @@ func GetPage[T any](items []T, first *int, after *string, last *int, before *str sIx = f eIx = idx } - page := items[sIx:eIx] + page := items[sIx:min(eIx, len(items))] return page, PageInfo{ StartCursor: ptr(EncodeCursor(fn(page[0]))), HasNextPage: eIx < len(items), diff --git a/pagination_test.go b/pagination_test.go index b7c4b40..b907d2b 100644 --- a/pagination_test.go +++ b/pagination_test.go @@ -39,6 +39,16 @@ func TestGetPage(t *testing.T) { EndCursor: ptr("Mg=="), }, }, + { + name: "first 10", + args: args[string]{items: []string{"1", "2", "3"}, first: ptr(10), max: 10, fn: func(s string) string { return s }}, + wantItems: []string{"1", "2", "3"}, + wantPageInfo: PageInfo{ + StartCursor: ptr("MQ=="), + HasNextPage: false, + EndCursor: ptr("Mw=="), + }, + }, { name: "after 2", args: args[string]{items: []string{"1", "2", "3", "4"}, first: ptr(2), after: ptr("Mg=="), max: 10, fn: func(s string) string { return s }},