client: fix Paginate's arguments validation (#6205)

Check both page and defLimit against negative values.

Follow up of #6205

Co-authored-by: Federico Kunze <31522760+fedekunze@users.noreply.github.com>
This commit is contained in:
Alessio Treglia 2020-05-13 14:14:43 +01:00 committed by GitHub
parent d9bcca2601
commit 9b6e694a00
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 28 additions and 6 deletions

View File

@ -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
}

View File

@ -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,
@ -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 {