add paging request
This commit is contained in:
@@ -13,7 +13,8 @@ repositories {
|
||||
|
||||
dependencies {
|
||||
implementation(libs.kotlinx.serialization.json)
|
||||
testImplementation(kotlin("test"))
|
||||
implementation(libs.bundles.ktor.server)
|
||||
implementation(libs.bundles.slf4j)
|
||||
}
|
||||
|
||||
tasks.test {
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
package ai.neuon.utility.paging
|
||||
|
||||
import io.ktor.server.request.ApplicationRequest
|
||||
import kotlin.math.max
|
||||
|
||||
sealed class PagingRequest {
|
||||
companion object {
|
||||
fun from(request: ApplicationRequest): PagingRequest {
|
||||
val params = request.queryParameters
|
||||
val pagingType = params["paging"]?.let {
|
||||
Type.from(it)
|
||||
} ?: Type.OFFSET
|
||||
|
||||
return when (pagingType) {
|
||||
Type.NONE -> None
|
||||
Type.OFFSET -> {
|
||||
val i = params["page"]?.toInt()
|
||||
?.let { max(0, it) } ?: 0
|
||||
val limit = params["pageSize"]?.toInt()
|
||||
?.let { max(1, it) } ?: 10
|
||||
Offset(index = i, limit = limit)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
data object None : PagingRequest()
|
||||
|
||||
data class Offset(val index: Int, val limit: Int) : PagingRequest() {
|
||||
val skip: Int
|
||||
get() = index * limit
|
||||
}
|
||||
|
||||
enum class Type(val key: String) {
|
||||
NONE(key = "none"), OFFSET(key = "offset");
|
||||
|
||||
companion object {
|
||||
/**
|
||||
* @throws IllegalArgumentException
|
||||
*/
|
||||
fun from(type: String): Type {
|
||||
return when (type) {
|
||||
"none" -> NONE
|
||||
"offset" -> OFFSET
|
||||
else -> throw IllegalArgumentException("Unsupported pagination type, $type")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user