Skip to content

Commit

Permalink
client: fix Paginate's arguments validation
Browse files Browse the repository at this point in the history
Check both page and defLimit against negative values.

Follow up of #6205
  • Loading branch information
Alessio Treglia committed May 12, 2020
1 parent b933002 commit 9416388
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 6 deletions.
19 changes: 13 additions & 6 deletions client/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,22 @@ package client

// Paginate returns the correct starting and ending index for a paginated query,
// given that client provides a desired page and limit of objects and the handler
// provides the total number of objects. If the start page is invalid, non-positive
// values are returned signaling the request is invalid.
//
// NOTE: The start page is assumed to be 1-indexed.
// provides the total number of objects. The start page is assumed to be 1-indexed.
// If the start page is invalid, non-positive values are returned signaling the
// request is invalid; it returns non-positive values if limit is non-positive and
// defLimit is negative.
func Paginate(numObjs, page, limit, defLimit int) (start, end int) {
if page == 0 {
if page <= 0 {
// invalid start page
return -1, -1
} else if limit == 0 {
}

// fallback to default limit if supplied limit is invalid
if limit <= 0 {
if defLimit < 0 {
// invalid default limit
return -1, -1
}
limit = defLimit
}

Expand Down
15 changes: 15 additions & 0 deletions client/utils_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,11 @@ func TestPaginate(t *testing.T) {
75, 2, 50, 100,
50, 75,
},
{
"fallback to default limit",
75, 5, 0, 10,
40, 50,
},
{
"invalid start page",
75, 4, 25, 100,
Expand All @@ -49,6 +54,16 @@ func TestPaginate(t *testing.T) {
75, 0, 25, 100,
-1, -1,
},
{
"invalid negative start page",
75, -1, 25, 100,
-1, -1,
},
{
"invalid default limit",
75, 2, 0, -10,
-1, -1,
},
}

for i, tc := range testCases {
Expand Down

0 comments on commit 9416388

Please sign in to comment.