Skip to content

Commit

Permalink
Fixed pager page and pages value when no items present.
Browse files Browse the repository at this point in the history
  • Loading branch information
mikestefanello committed Sep 13, 2024
1 parent f54d9f8 commit a931955
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 2 deletions.
8 changes: 7 additions & 1 deletion pkg/page/pager.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ type Pager struct {
func NewPager(ctx echo.Context, itemsPerPage int) Pager {
p := Pager{
ItemsPerPage: itemsPerPage,
Pages: 1,
Page: 1,
}

Expand All @@ -53,7 +54,12 @@ func NewPager(ctx echo.Context, itemsPerPage int) Pager {
// This should be used rather than setting either items or pages directly.
func (p *Pager) SetItems(items int) {
p.Items = items
p.Pages = int(math.Ceil(float64(items) / float64(p.ItemsPerPage)))

if items > 0 {
p.Pages = int(math.Ceil(float64(items) / float64(p.ItemsPerPage)))
} else {
p.Pages = 1
}

if p.Page > p.Pages {
p.Page = p.Pages
Expand Down
7 changes: 6 additions & 1 deletion pkg/page/pager_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ func TestNewPager(t *testing.T) {
assert.Equal(t, 10, pgr.ItemsPerPage)
assert.Equal(t, 1, pgr.Page)
assert.Equal(t, 0, pgr.Items)
assert.Equal(t, 0, pgr.Pages)
assert.Equal(t, 1, pgr.Pages)

ctx, _ = tests.NewContext(e, fmt.Sprintf("/abc?%s=%d", PageQueryKey, 2))
pgr = NewPager(ctx, 10)
Expand All @@ -34,6 +34,11 @@ func TestPager_SetItems(t *testing.T) {
pgr.SetItems(100)
assert.Equal(t, 100, pgr.Items)
assert.Equal(t, 5, pgr.Pages)

pgr.SetItems(0)
assert.Equal(t, 0, pgr.Items)
assert.Equal(t, 1, pgr.Pages)
assert.Equal(t, 1, pgr.Page)
}

func TestPager_IsBeginning(t *testing.T) {
Expand Down

0 comments on commit a931955

Please sign in to comment.