Last active
August 25, 2017 20:37
-
-
Save codemwnci/8a47b66dd7ef2cdc2cca461176115169 to your computer and use it in GitHub Desktop.
Create a new Todo, plus some helper classes / functions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fun main(args: Array<String>) { | |
setupDB() | |
port(9000) | |
staticFileLocation("/public/") | |
path("/todo/") { | |
data class Todo(val id: Long, val text: String, val done: Boolean, val createdAt: LocalDateTime) | |
val toTodo: (Row) -> Todo = { row -> Todo(row.long(1), row.string(2), row.boolean(3), row.localDateTime(4))} | |
fun getTodo(id: Long): Todo? = using(sessionOf(HikariCP.dataSource())) { session -> | |
session.run(queryOf("select id, text, done, created_at from todo where id=?", id).map(toTodo).asSingle) | |
} | |
post("") { req, res -> | |
if (req.body().isNullOrEmpty()) badRequest("a todo cannot be blank") | |
val todo = req.body() | |
val id = using(sessionOf(HikariCP.dataSource())) { session -> | |
session.run(queryOf("insert into todo (text) values(?)", todo).asUpdateAndReturnGeneratedKey) | |
} | |
if (id == null) internalServerError("there was a problem creating the Todo") | |
else jacksonObjectMapper().writeValueAsString( getTodo(id) ) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment