github.com/leg100/ots@v0.0.7-0.20210919080622-034055ced4bd/pagination.go (about) 1 package ots 2 3 import ( 4 "math" 5 6 tfe "github.com/leg100/go-tfe" 7 ) 8 9 // SanitizeListOptions ensures list options adhere to mins and maxs 10 func SanitizeListOptions(opts *tfe.ListOptions) { 11 if opts.PageNumber == 0 { 12 opts.PageNumber = 1 13 } 14 15 switch { 16 case opts.PageSize > 100: 17 opts.PageSize = MaxPageSize 18 case opts.PageSize <= 0: 19 opts.PageSize = DefaultPageSize 20 } 21 } 22 23 // NewPagination constructs a Pagination obj. 24 func NewPagination(opts tfe.ListOptions, count int) *tfe.Pagination { 25 SanitizeListOptions(&opts) 26 27 return &tfe.Pagination{ 28 CurrentPage: opts.PageNumber, 29 PreviousPage: previousPage(opts.PageNumber), 30 NextPage: nextPage(opts, count), 31 TotalPages: totalPages(count, opts.PageSize), 32 TotalCount: count, 33 } 34 } 35 36 func totalPages(totalCount, pageSize int) int { 37 return int(math.Max(1, math.Ceil(float64(totalCount)/float64(pageSize)))) 38 } 39 40 func previousPage(currentPage int) int { 41 if currentPage > 1 { 42 return currentPage - 1 43 } 44 return 1 45 } 46 47 func nextPage(opts tfe.ListOptions, count int) int { 48 if opts.PageNumber < totalPages(count, opts.PageSize) { 49 return opts.PageNumber + 1 50 } 51 return 1 52 }