From fce1cc0e9c63197895fa8fdf840213d82d826d90 Mon Sep 17 00:00:00 2001 From: Hubert Van De Walle Date: Mon, 20 Apr 2020 15:19:25 +0200 Subject: [PATCH] WIP --- api/src/controllers/ChaptersController.kt | 88 +++++++++++++++++++++++ 1 file changed, 88 insertions(+) create mode 100644 api/src/controllers/ChaptersController.kt diff --git a/api/src/controllers/ChaptersController.kt b/api/src/controllers/ChaptersController.kt new file mode 100644 index 0000000..ceb409b --- /dev/null +++ b/api/src/controllers/ChaptersController.kt @@ -0,0 +1,88 @@ +package be.vandewalleh.controllers + +import be.vandewalleh.entities.User +import be.vandewalleh.tables.Chapters +import be.vandewalleh.tables.Notes +import be.vandewalleh.tables.Users +import io.ktor.application.ApplicationCall +import io.ktor.application.call +import io.ktor.http.HttpStatusCode +import io.ktor.request.receive +import io.ktor.routing.Route +import io.ktor.routing.post +import me.liuwj.ktorm.database.Database +import me.liuwj.ktorm.dsl.* +import me.liuwj.ktorm.entity.find +import me.liuwj.ktorm.entity.sequenceOf +import org.kodein.di.Kodein +import org.kodein.di.generic.instance + +class ChaptersController(kodein: Kodein) : AuthCrudController("/notes/{noteTitle}/chapters/{chapterNumber}", kodein) { + private val db by kodein.instance() + + private fun ApplicationCall.noteTitle(): String? { + return this.parameters["noteTitle"]!! + } + + private fun ApplicationCall.chapterNumber(): Int? { + return this.parameters["chapterNumber"]?.toIntOrNull() + } + + private fun ApplicationCall.chapterExists(): Boolean { + val user = user() + val title = noteTitle() ?: error("title missing") + val noteId = requestedNoteId() ?: error("") + + + + return db.from(Chapters) + .select(Chapters.id) + .where { Notes.userId eq user.id and (Notes.id eq noteId) } + .limit(0, 1) + .map { it[Notes.id]!! } + .firstOrNull() != null + } + + private fun ApplicationCall.user(): User { + return db.sequenceOf(Users) + .find { it.email eq this.userEmail() } + ?: error("") + } + + /** + * Method that returns a [Notes] ID from it's title and the currently logged in user. + * returns null if none found + */ + private fun ApplicationCall.requestedNoteId(): Int? { + val user = user() + val title = noteTitle() ?: error("title missing") + + return db.from(Notes) + .select(Notes.id) + .where { Notes.userId eq user.id and (Notes.title eq title) } + .limit(0, 1) + .map { it[Notes.id]!! } + .firstOrNull() + } + + + private data class PostRequestBody(val title: String, val content: String) + + override val route: Route.() -> Unit = { + post { + val noteId = call.requestedNoteId() + ?: return@post call.respondStatus(HttpStatusCode.NotFound) + + val chapterNumber = call.chapterNumber() + ?:return@post call.respondStatus(HttpStatusCode.BadRequest) + + val exists = + + + val (title, content) = call.receive() + + if() + + } + } +}