github.com/kyma-incubator/compass/components/director@v0.0.0-20230623144113-d764f56ff805/pkg/pagination/pagination.go (about) 1 package pagination 2 3 import ( 4 "encoding/base64" 5 "fmt" 6 "strconv" 7 "strings" 8 9 "github.com/kyma-incubator/compass/components/director/pkg/apperrors" 10 11 "github.com/pkg/errors" 12 ) 13 14 const surprise = "DpKtJ4j9jDq" 15 16 // Page missing godoc 17 type Page struct { 18 StartCursor string 19 EndCursor string 20 HasNextPage bool 21 } 22 23 // DecodeOffsetCursor missing godoc 24 func DecodeOffsetCursor(cursor string) (int, error) { 25 if cursor == "" { 26 return 0, nil 27 } 28 29 decodedValue, err := base64.StdEncoding.DecodeString(cursor) 30 if err != nil { 31 return 0, errors.Wrap(err, "cursor is not correct") 32 } 33 34 realCursor := strings.TrimPrefix(string(decodedValue), surprise) 35 36 offset, err := strconv.Atoi(realCursor) 37 if err != nil { 38 return 0, errors.Wrap(err, "cursor is not correct") 39 } 40 41 if offset < 0 { 42 return 0, apperrors.NewInvalidDataError("cursor is not correct") 43 } 44 45 return offset, nil 46 } 47 48 // EncodeNextOffsetCursor missing godoc 49 func EncodeNextOffsetCursor(offset, pageSize int) string { 50 nextPage := pageSize + offset 51 52 cursor := surprise + strconv.Itoa(nextPage) 53 54 return base64.StdEncoding.EncodeToString([]byte(cursor)) 55 } 56 57 // ConvertOffsetLimitAndOrderedColumnToSQL missing godoc 58 func ConvertOffsetLimitAndOrderedColumnToSQL(pageSize, offset int, orderedColumn string) (string, error) { 59 if orderedColumn == "" { 60 return "", apperrors.NewInvalidDataError("to use pagination you must provide column to order by") 61 } 62 63 if pageSize < 1 { 64 return "", apperrors.NewInvalidDataError("page size cannot be smaller than 1") 65 } 66 67 if offset < 0 { 68 return "", apperrors.NewInvalidDataError("offset cannot be smaller than 0") 69 } 70 71 return fmt.Sprintf(`ORDER BY %s LIMIT %d OFFSET %d`, orderedColumn, pageSize, offset), nil 72 }