generated from ministryofjustice/hmpps-template-kotlin
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
CDPS-112: Fix pagination page and move to new class
- Loading branch information
1 parent
f8d0e1a
commit 04321ae
Showing
2 changed files
with
65 additions
and
26 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
45 changes: 45 additions & 0 deletions
45
src/main/kotlin/uk/gov/justice/digital/hmpps/healthandmedication/utils/Pagination.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,45 @@ | ||
package uk.gov.justice.digital.hmpps.healthandmedication.utils | ||
|
||
class Pagination { | ||
data class PaginationMetadata( | ||
val first: Boolean, | ||
val last: Boolean, | ||
val numberOfElements: Int, | ||
val offset: Int, | ||
val pageNumber: Int, | ||
val size: Int, | ||
val totalElements: Int, | ||
val totalPages: Int, | ||
) | ||
|
||
data class PaginatedCollection<TCollection>( | ||
val content: List<TCollection>, | ||
val metadata: PaginationMetadata, | ||
) | ||
|
||
companion object { | ||
fun <TCollection> paginateCollection( | ||
page: Int, | ||
pageSize: Int, | ||
collection: List<TCollection>, | ||
): PaginatedCollection<TCollection> { | ||
val startIndex = (page - 1) * pageSize | ||
val lastIndex = (startIndex + pageSize- 1).coerceAtMost(collection.size - 1) | ||
val content = collection.slice(startIndex..lastIndex) | ||
|
||
return PaginatedCollection( | ||
content, | ||
PaginationMetadata( | ||
first = startIndex == 0, | ||
last = (lastIndex + 1) >= collection.size, | ||
numberOfElements = content.size, | ||
offset = startIndex, | ||
pageNumber = page, | ||
size = pageSize, | ||
totalElements = collection.size, | ||
totalPages = Math.ceilDiv(collection.size, pageSize).coerceAtLeast(1), | ||
), | ||
) | ||
} | ||
} | ||
} |