fix validate pagination params
This commit is contained in:
parent
8d60a5a7bd
commit
6f9867cba6
|
@ -124,10 +124,14 @@ func SetEventBus(b *types.EventBus) {
|
|||
eventBus = b
|
||||
}
|
||||
|
||||
func validatePage(page int) int {
|
||||
func validatePage(page, perPage, totalCount int) int {
|
||||
pages := ((totalCount - 1) / perPage) + 1
|
||||
if page < 1 {
|
||||
return 1
|
||||
page = 1
|
||||
} else if page > pages {
|
||||
page = pages
|
||||
}
|
||||
|
||||
return page
|
||||
}
|
||||
|
||||
|
|
|
@ -0,0 +1,67 @@
|
|||
package core
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestPaginationPage(t *testing.T) {
|
||||
|
||||
cases := []struct {
|
||||
totalCount int
|
||||
perPage int
|
||||
page int
|
||||
newPage int
|
||||
}{
|
||||
{0, 10, 0, 1},
|
||||
{0, 10, 1, 1},
|
||||
{0, 10, 2, 1},
|
||||
|
||||
{5, 10, -1, 1},
|
||||
{5, 10, 0, 1},
|
||||
{5, 10, 1, 1},
|
||||
{5, 10, 2, 1},
|
||||
{5, 10, 2, 1},
|
||||
|
||||
{5, 5, 1, 1},
|
||||
{5, 5, 2, 1},
|
||||
{5, 5, 3, 1},
|
||||
|
||||
{5, 3, 2, 2},
|
||||
{5, 3, 3, 2},
|
||||
|
||||
{5, 2, 2, 2},
|
||||
{5, 2, 3, 3},
|
||||
{5, 2, 4, 3},
|
||||
}
|
||||
|
||||
for _, c := range cases {
|
||||
p := validatePage(c.page, c.perPage, c.totalCount)
|
||||
assert.Equal(t, c.newPage, p, fmt.Sprintf("%v", c))
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func TestPaginationPerPage(t *testing.T) {
|
||||
|
||||
cases := []struct {
|
||||
totalCount int
|
||||
perPage int
|
||||
newPerPage int
|
||||
}{
|
||||
{5, 0, defaultPerPage},
|
||||
{5, 1, 1},
|
||||
{5, 2, 2},
|
||||
{5, defaultPerPage, defaultPerPage},
|
||||
{5, maxPerPage - 1, maxPerPage - 1},
|
||||
{5, maxPerPage, maxPerPage},
|
||||
{5, maxPerPage + 1, defaultPerPage},
|
||||
}
|
||||
|
||||
for _, c := range cases {
|
||||
p := validatePerPage(c.perPage)
|
||||
assert.Equal(t, c.newPerPage, p, fmt.Sprintf("%v", c))
|
||||
}
|
||||
}
|
|
@ -188,7 +188,7 @@ func TxSearch(query string, prove bool, page, perPage int) (*ctypes.ResultTxSear
|
|||
}
|
||||
|
||||
totalCount := len(results)
|
||||
page = validatePage(page)
|
||||
page = validatePage(page, perPage, totalCount)
|
||||
perPage = validatePerPage(perPage)
|
||||
skipCount := (page - 1) * perPage
|
||||
|
||||
|
|
Loading…
Reference in New Issue