pagination.go 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  1. //go:build go1.18
  2. // +build go1.18
  3. /*
  4. Until go version 2, we can't really apply the type alias feature on a generic type or function,
  5. so keep it separated on x/pagination.
  6. import "github.com/kataras/iris/v12/context"
  7. type ListResponse[T any] = context.ListResponse[T]
  8. OR
  9. type ListResponse = context.ListResponse doesn't work.
  10. The only workable thing for generic aliases is when you know the type e.g.
  11. type ListResponse = context.ListResponse[any] but that doesn't fit us.
  12. */
  13. package pagination
  14. import (
  15. "math"
  16. "net/http"
  17. "strconv"
  18. )
  19. var (
  20. // MaxSize defines the max size of items to display.
  21. MaxSize = 100000
  22. // DefaultSize defines the default size when ListOptions.Size is zero.
  23. DefaultSize = MaxSize
  24. )
  25. // ListOptions is the list request object which should be provided by the client through
  26. // URL Query. Then the server passes that options to a database query,
  27. // including any custom filters may be given from the request body and,
  28. // then the server responds back with a `Context.JSON(NewList(...))` response based
  29. // on the database query's results.
  30. type ListOptions struct {
  31. // Current page number.
  32. // If Page > 0 then:
  33. // Limit = DefaultLimit
  34. // Offset = DefaultLimit * Page
  35. // If Page == 0 then no actual data is return,
  36. // internally we must check for this value
  37. // because in postgres LIMIT 0 returns the columns but with an empty set.
  38. Page int `json:"page" url:"page"`
  39. // The elements to get, this modifies the LIMIT clause,
  40. // this Size can't be higher than the MaxSize.
  41. // If Size is zero then size is set to DefaultSize.
  42. Size int `json:"size" url:"size"`
  43. }
  44. // GetLimit returns the LIMIT value of a query.
  45. func (opts ListOptions) GetLimit() int {
  46. if opts.Size > 0 && opts.Size < MaxSize {
  47. return opts.Size
  48. }
  49. return DefaultSize
  50. }
  51. // GetLimit returns the OFFSET value of a query.
  52. func (opts ListOptions) GetOffset() int {
  53. if opts.Page > 1 {
  54. return (opts.Page - 1) * opts.GetLimit()
  55. }
  56. return 0
  57. }
  58. // GetCurrentPage returns the Page or 1.
  59. func (opts ListOptions) GetCurrentPage() int {
  60. current := opts.Page
  61. if current == 0 {
  62. current = 1
  63. }
  64. return current
  65. }
  66. // GetNextPage returns the next page, current page + 1.
  67. func (opts ListOptions) GetNextPage() int {
  68. return opts.GetCurrentPage() + 1
  69. }
  70. // Bind binds the ListOptions values to a request value.
  71. // It should be used as an x/client.RequestOption to fire requests
  72. // on a server that supports pagination.
  73. func (opts ListOptions) Bind(r *http.Request) error {
  74. page := strconv.Itoa(opts.GetCurrentPage())
  75. size := strconv.Itoa(opts.GetLimit())
  76. q := r.URL.Query()
  77. q.Set("page", page)
  78. q.Set("size", size)
  79. return nil
  80. }
  81. // List is the http response of a server handler which should render
  82. // items with pagination support.
  83. type List[T any] struct {
  84. CurrentPage int `json:"current_page"` // the current page.
  85. PageSize int `json:"page_size"` // the total amount of the entities return.
  86. TotalPages int `json:"total_pages"` // the total number of pages based on page, size and total count.
  87. TotalItems int64 `json:"total_items"` // the total number of rows.
  88. HasNextPage bool `json:"has_next_page"` // true if more data can be fetched, depending on the current page * page size and total pages.
  89. Filter any `json:"filter"` // if any filter data.
  90. Items []T `json:"items"` // Items is empty array if no objects returned. Do NOT modify from outside.
  91. }
  92. // NewList returns a new List response which holds
  93. // the current page, page size, total pages, total items count, any custom filter
  94. // and the items array.
  95. //
  96. // Example Code:
  97. //
  98. // import "github.com/kataras/iris/v12/x/pagination"
  99. // ...more code
  100. //
  101. // type User struct {
  102. // Firstname string `json:"firstname"`
  103. // Lastname string `json:"lastname"`
  104. // }
  105. //
  106. // type ExtraUser struct {
  107. // User
  108. // ExtraData string
  109. // }
  110. //
  111. // func main() {
  112. // users := []User{
  113. // {"Gerasimos", "Maropoulos"},
  114. // {"Efi", "Kwfidou"},
  115. // }
  116. //
  117. // t := pagination.NewList(users, 100, nil, pagination.ListOptions{
  118. // Page: 1,
  119. // Size: 50,
  120. // })
  121. //
  122. // // Optionally, transform a T list of objects to a V list of objects.
  123. // v, err := pagination.TransformList(t, func(u User) (ExtraUser, error) {
  124. // return ExtraUser{
  125. // User: u,
  126. // ExtraData: "test extra data",
  127. // }, nil
  128. // })
  129. // if err != nil { panic(err) }
  130. //
  131. // paginationJSON, err := json.MarshalIndent(v, "", " ")
  132. // if err!=nil { panic(err) }
  133. // fmt.Println(paginationJSON)
  134. // }
  135. func NewList[T any](items []T, totalCount int64, filter any, opts ListOptions) *List[T] {
  136. pageSize := opts.GetLimit()
  137. n := len(items)
  138. if n == 0 || pageSize <= 0 {
  139. return &List[T]{
  140. CurrentPage: 1,
  141. PageSize: 0,
  142. TotalItems: 0,
  143. TotalPages: 0,
  144. Filter: filter,
  145. Items: make([]T, 0),
  146. }
  147. }
  148. numberOfPages := int(roundUp(float64(totalCount)/float64(pageSize), 0))
  149. if numberOfPages <= 0 {
  150. numberOfPages = 1
  151. }
  152. var hasNextPage bool
  153. currentPage := opts.GetCurrentPage()
  154. if totalCount == 0 {
  155. currentPage = 1
  156. }
  157. if n > 0 {
  158. hasNextPage = currentPage < numberOfPages
  159. }
  160. return &List[T]{
  161. CurrentPage: currentPage,
  162. PageSize: n,
  163. TotalPages: numberOfPages,
  164. TotalItems: totalCount,
  165. HasNextPage: hasNextPage,
  166. Filter: filter,
  167. Items: items,
  168. }
  169. }
  170. // TransformList accepts a List response and converts to a list of V items.
  171. // T => from
  172. // V => to
  173. //
  174. // Example Code:
  175. //
  176. // listOfUsers := pagination.NewList(...)
  177. // newListOfExtraUsers, err := pagination.TransformList(listOfUsers, func(u User) (ExtraUser, error) {
  178. // return ExtraUser{
  179. // User: u,
  180. // ExtraData: "test extra data",
  181. // }, nil
  182. // })
  183. func TransformList[T any, V any](list *List[T], transform func(T) (V, error)) (*List[V], error) {
  184. if list == nil {
  185. return &List[V]{
  186. CurrentPage: 1,
  187. PageSize: 0,
  188. TotalItems: 0,
  189. TotalPages: 0,
  190. Filter: nil,
  191. Items: make([]V, 0),
  192. }, nil
  193. }
  194. items := list.Items
  195. toItems := make([]V, 0, len(items))
  196. for _, fromItem := range items {
  197. toItem, err := transform(fromItem)
  198. if err != nil {
  199. return nil, err
  200. }
  201. toItems = append(toItems, toItem)
  202. }
  203. newList := &List[V]{
  204. CurrentPage: list.CurrentPage,
  205. PageSize: list.PageSize,
  206. TotalItems: list.TotalItems,
  207. TotalPages: list.TotalPages,
  208. Filter: list.Filter,
  209. Items: toItems,
  210. }
  211. return newList, nil
  212. }
  213. func roundUp(input float64, places float64) float64 {
  214. pow := math.Pow(10, places)
  215. return math.Ceil(pow*input) / pow
  216. }