66 lines
1.9 KiB
Kotlin
66 lines
1.9 KiB
Kotlin
package com.jaytux.simd.server
|
|
|
|
import com.jaytux.simd.data.*
|
|
import io.ktor.http.*
|
|
import io.ktor.server.application.*
|
|
import io.ktor.server.plugins.autohead.*
|
|
import io.ktor.server.response.*
|
|
import io.ktor.server.routing.*
|
|
import kotlinx.serialization.Serializable
|
|
import org.jetbrains.exposed.sql.*
|
|
import org.jetbrains.exposed.sql.transactions.transaction
|
|
import java.util.*
|
|
|
|
@Serializable data class ErrorResponse(val error: String)
|
|
class HttpError(msg: String, val status: HttpStatusCode = HttpStatusCode.BadRequest) : Exception(msg)
|
|
|
|
inline suspend fun <reified R: Any> RoutingContext.runCatching(crossinline block: suspend RoutingContext.() -> R) {
|
|
try {
|
|
call.respond(block())
|
|
}
|
|
catch(err: HttpError) {
|
|
call.respond(err.status, ErrorResponse(err.message ?: "<no error message given>"))
|
|
}
|
|
}
|
|
|
|
inline fun <reified T, reified R> Route.getPagedUrl(
|
|
path: String,
|
|
crossinline perPage: RoutingContext.() -> Int,
|
|
crossinline mapper: (T) -> R,
|
|
crossinline getSet: RoutingContext.() -> SizedIterable<T>,
|
|
) {
|
|
get(path) {
|
|
runCatching {
|
|
transaction { getSet().paginated(0, perPage(), mapper) }
|
|
}
|
|
}
|
|
get("$path/{page}") {
|
|
runCatching {
|
|
val page = call.parameters["page"]?.toLongOrNull() ?: 0
|
|
transaction { getSet().paginated(page, perPage(), mapper) }
|
|
}
|
|
}
|
|
}
|
|
|
|
inline fun <reified T, reified R> Route.getPagedRequest(
|
|
path: String,
|
|
crossinline perPage: RoutingContext.() -> Int,
|
|
crossinline mapper: (T) -> R,
|
|
crossinline getSet: RoutingContext.() -> SizedIterable<T>,
|
|
) {
|
|
get(path) {
|
|
runCatching {
|
|
val page = call.request.queryParameters["page"]?.toLongOrNull() ?: 0
|
|
transaction { getSet().paginated(page, perPage(), mapper) }
|
|
}
|
|
}
|
|
}
|
|
|
|
fun Application.configureRouting() {
|
|
install(AutoHeadResponse)
|
|
routing {
|
|
installGetAll()
|
|
installSearch()
|
|
installDetails()
|
|
}
|
|
} |