Initial API

This commit is contained in:
2025-04-21 11:27:13 +02:00
commit 5f91256c31
23 changed files with 1317 additions and 0 deletions

View File

@ -0,0 +1,66 @@
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()
}
}