74 lines
2.2 KiB
Kotlin
74 lines
2.2 KiB
Kotlin
package be.vandewalleh.controllers
|
|
|
|
import be.vandewalleh.entities.Note
|
|
import be.vandewalleh.entities.Tag
|
|
import be.vandewalleh.errors.ApiError
|
|
import be.vandewalleh.tables.Notes
|
|
import be.vandewalleh.tables.Tags
|
|
import be.vandewalleh.tables.Users
|
|
import io.ktor.application.call
|
|
import io.ktor.auth.UserIdPrincipal
|
|
import io.ktor.auth.authenticate
|
|
import io.ktor.auth.principal
|
|
import io.ktor.http.HttpStatusCode
|
|
import io.ktor.locations.Location
|
|
import io.ktor.locations.post
|
|
import io.ktor.request.receive
|
|
import io.ktor.response.respond
|
|
import io.ktor.routing.Routing
|
|
import me.liuwj.ktorm.database.Database
|
|
import me.liuwj.ktorm.dsl.eq
|
|
import me.liuwj.ktorm.entity.add
|
|
import me.liuwj.ktorm.entity.find
|
|
import me.liuwj.ktorm.entity.sequenceOf
|
|
import org.kodein.di.Kodein
|
|
import org.kodein.di.generic.instance
|
|
|
|
class NoteController(kodein: Kodein) : KodeinController(kodein) {
|
|
private val db by instance<Database>()
|
|
|
|
override fun Routing.registerRoutes() {
|
|
authenticate {
|
|
post<Routes.Notes> {
|
|
data class Response(val message: String)
|
|
|
|
val (email) = call.principal<UserIdPrincipal>()!!
|
|
val body = call.receive<PostNotesBody>()
|
|
|
|
val user = db.sequenceOf(Users)
|
|
.find { Users.email eq email }
|
|
?: return@post call.respond(HttpStatusCode.Forbidden, ApiError.DeletedUserError)
|
|
|
|
val transaction = db.useTransaction {
|
|
|
|
val note = Note {
|
|
this.title = body.title
|
|
this.content = body.content
|
|
this.user = user
|
|
}
|
|
|
|
db.sequenceOf(Notes).add(note)
|
|
|
|
body.tags.forEach { tagName ->
|
|
val tag = Tag {
|
|
this.name = tagName
|
|
this.note = note
|
|
}
|
|
db.sequenceOf(Tags).add(tag)
|
|
}
|
|
1
|
|
}
|
|
|
|
return@post call.respond(Response("created"))
|
|
}
|
|
}
|
|
|
|
}
|
|
|
|
object Routes {
|
|
@Location("/notes")
|
|
class Notes
|
|
}
|
|
}
|
|
|
|
data class PostNotesBody(val title: String, val content: String, val tags: List<String>) |