Шаблон REST

inline fun <reified T : Any> Route.repoRoutes(
    repo: Repo<T>
) {

Сериализация

val serializer: KSerializer<T> = serializer()
val itemSerializer: KSerializer<Item<T>> = serializer()
val listItemSerializer = ListSerializer(itemSerializer)

Get

get {
    val elemList: List<Item<T>> = repo.read()
    if (elemList.isEmpty()) {
        call.respondText(
            "No element found", 
            status = HttpStatusCode.NotFound)
    } else {
        val elemJson = Json.encodeToString(
            listItemSerializer, 
            elemList)
        call.respond(elemJson)
    }
}

Список элементов

post("byId") {
    val ids = try {
        call.receive<List<String>>()
    } catch (e: Throwable) {
        return@post call.respondText(
            "Request body is not list id", 
            status = HttpStatusCode.BadRequest)
    }
    val elements = Json.encodeToString(
        listItemSerializer, 
        repo.read(ids))
    call.respond(elements)
}

studentRoutes

repoRoutes(studentsRepo)
get("ByStartName/{startName}") {
    val startName =
        call.parameters["startName"] ?: 
            return@get call.respondText(
                "Missing or malformed startName",
                status = HttpStatusCode.BadRequest)
    val students = studentsRepo.read().filter {
        it.elem.firstname.startsWith(startName)}
    if (students.isEmpty()) {
        call.respondText(
            "No students found", 
            status = HttpStatusCode.NotFound)
    } else { call.respond(students) }}

lessonRoutes

repoRoutes(lessonsRepo)
get("{idL}/students/{idS}") {
    val idL = call.parameters["idL"]
        ?: return@get call.respondText(
            "Missing or malformed lesson id",
            status = HttpStatusCode.BadRequest)
    val lesson = lessonsRepo.read(listOf(idL)).getOrNull(0)
        ?: return@get call.respondText(
            "No lesson with id $idL",
            status = HttpStatusCode.NotFound)
    val idS = call.parameters["idS"] 
        ?: return@get call.respondText(
            "Missing or malformed student id",
            status = HttpStatusCode.BadRequest)

lessonRoutes

studentsRepo.read(listOf(idS)).getOrNull(0)
    ?: return@get call.respondText(
        "No student with id $idS",
        status = HttpStatusCode.NotFound)
if (lesson.elem.students.find { it.studentId == idS } != null)
    return@get call.respondText(
        "Student already in lesson",
        status = HttpStatusCode.BadRequest)
val newLesson = lesson.elem.addStudent(idS)
lessonsRepo.update(lesson.id, newLesson)
call.respondText(
    "Student added correctly",
    status = HttpStatusCode.OK) }