Files
summercms/lagoon/paginate.go
Jakub Zych 52638fb4e3 feat(05-01): add Paginate envelope and RegisterJoinTable
- Page/PageMeta emit {data, meta} with no links key
- RegisterJoinTable fails loud on nil db; document pivot-write contract
2026-09-18 18:47:42 +02:00

41 lines
1018 B
Go

package lagoon
// PageMeta is the pagination block of the house REST envelope (DATA-10).
type PageMeta struct {
CurrentPage int `json:"current_page"`
LastPage int `json:"last_page"`
PerPage int `json:"per_page"`
Total int64 `json:"total"`
}
// Page wraps already-built row DTOs. There is no links field.
type Page[T any] struct {
Data []T `json:"data"`
Meta PageMeta `json:"meta"`
}
// Paginate builds {data, meta{current_page,last_page,per_page,total}} from
// a caller-sliced row set. LastPage is ceil(total/perPage); perPage<=0
// yields LastPage 1 instead of dividing by zero. Nil rows become [].
func Paginate[T any](rows []T, page, perPage int, total int64) Page[T] {
last := 1
if perPage > 0 {
last = int((total + int64(perPage) - 1) / int64(perPage))
if last < 1 {
last = 1
}
}
if rows == nil {
rows = []T{}
}
return Page[T]{
Data: rows,
Meta: PageMeta{
CurrentPage: page,
LastPage: last,
PerPage: perPage,
Total: total,
},
}
}