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 RoutingContext.runCatching(crossinline block: suspend RoutingContext.() -> R) { try { call.respond(block()) } catch(err: HttpError) { call.respond(err.status, ErrorResponse(err.message ?: "")) } } inline fun Route.getPagedUrl( path: String, crossinline perPage: RoutingContext.() -> Int, crossinline mapper: (T) -> R, crossinline getSet: RoutingContext.() -> SizedIterable, ) { 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 Route.getPagedRequest( path: String, crossinline perPage: RoutingContext.() -> Int, crossinline mapper: (T) -> R, crossinline getSet: RoutingContext.() -> SizedIterable, ) { 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() } }