Skip to content

Commit

Permalink
feat(pagination): add helpers (#1451)
Browse files Browse the repository at this point in the history
  • Loading branch information
hekike authored Sep 2, 2024
1 parent 857a9bb commit 116ae76
Showing 1 changed file with 59 additions and 0 deletions.
59 changes: 59 additions & 0 deletions pkg/pagination/pagination.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,31 @@ type Page struct {
PageNumber int `json:"page"`
}

// NewPage creates a new Page with the given pageNumber and pageSize.
func NewPage(pageNumber int, pageSize int) Page {
return Page{
PageSize: pageSize,
PageNumber: pageNumber,
}
}

// NewPageFromRef creates a new Page from pointers to pageNumber and pageSize.
// Useful for handling query parameters.
func NewPageFromRef(pageNumber *int, pageSize *int) Page {
pn := 0
ps := 0

if pageNumber != nil {
pn = *pageNumber
}

if pageSize != nil {
ps = *pageSize
}

return NewPage(pn, ps)
}

func (p Page) Offset() int {
return p.PageSize * (p.PageNumber - 1)
}
Expand Down Expand Up @@ -50,6 +75,40 @@ type PagedResponse[T any] struct {
Items []T `json:"items"`
}

// MapPagedResponse creates a new PagedResponse with the given page, totalCount and items.
func MapPagedResponse[Out any, In any](resp PagedResponse[In], m func(in In) Out) PagedResponse[Out] {
items := make([]Out, 0, len(resp.Items))
for _, inItem := range resp.Items {
items = append(items, m(inItem))
}

return PagedResponse[Out]{
Page: resp.Page,
TotalCount: resp.TotalCount,
Items: items,
}
}

// MapPagedResponseError is similar to MapPagedResponse
// but it allows the mapping function to return an error.
func MapPagedResponseError[Out any, In any](resp PagedResponse[In], m func(in In) (Out, error)) (PagedResponse[Out], error) {
items := make([]Out, 0, len(resp.Items))
for _, inItem := range resp.Items {
item, err := m(inItem)
if err != nil {
return PagedResponse[Out]{}, err
}

items = append(items, item)
}

return PagedResponse[Out]{
Page: resp.Page,
TotalCount: resp.TotalCount,
Items: items,
}, nil
}

// Implement json.Marshaler interface to flatten the Page struct
func (p PagedResponse[T]) MarshalJSON() ([]byte, error) {
type Alias PagedResponse[T]
Expand Down

0 comments on commit 116ae76

Please sign in to comment.