Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
gitpod-io
GitHub Repository: gitpod-io/gitpod
Path: blob/main/components/public-api-server/pkg/apiv1/pagination.go
2499 views
1
// Copyright (c) 2022 Gitpod GmbH. All rights reserved.
2
// Licensed under the GNU Affero General Public License (AGPL).
3
// See License.AGPL.txt in the project root for license information.
4
5
package apiv1
6
7
import (
8
db "github.com/gitpod-io/gitpod/components/gitpod-db/go"
9
v1 "github.com/gitpod-io/gitpod/components/public-api/go/experimental/v1"
10
)
11
12
func validatePagination(p *v1.Pagination) *v1.Pagination {
13
pagination := &v1.Pagination{
14
PageSize: 25,
15
Page: 1,
16
}
17
18
if p == nil {
19
return pagination
20
}
21
22
if p.Page > 0 {
23
pagination.Page = p.Page
24
}
25
if p.PageSize > 0 && p.PageSize <= 100 {
26
pagination.PageSize = p.PageSize
27
}
28
29
return pagination
30
}
31
32
func paginationToDB(p *v1.Pagination) db.Pagination {
33
validated := validatePagination(p)
34
return db.Pagination{
35
Page: int(validated.GetPage()),
36
PageSize: int(validated.GetPageSize()),
37
}
38
}
39
40
func pageFromResults[T any](results []T, p *v1.Pagination) []T {
41
pagination := validatePagination(p)
42
43
size := len(results)
44
45
start := int((pagination.Page - 1) * pagination.PageSize)
46
end := int(pagination.Page * pagination.PageSize)
47
48
if start > size {
49
return nil
50
}
51
52
if end > size {
53
end = size
54
}
55
56
return results[start:end]
57
}
58
59