how can i make this easier for myself?
# codereview
h
how can i make this easier for myself?
p
You have created list
props
, updated it, but never used it. Seems like a bug? 🙂 I guess you can create local function that will get param by name from context and will nullify it if it is empty. Something like this (I didn’t test):
Copy code
fun getParam(name: String): String? {
    val value = ctx.formParam(name)
    return if (value == "") null else value 
}
Or you can put this function into context class or make it extension function, whatever makes sense in your case.
h
oh yeah, i could’ve just made the list and ran it with that. Thanks for that function as well! That will make things easier. Just a question, is my indentation for the book properties acceptable, or discouraged
Copy code
<http://app.post|app.post>("/new-book-manual") manual@{ ctx ->
    val title = ctx getParam "title"?: return@manual
    val author = ctx getParam "author"?: return@manual
    val edition = ctx getParam "edition"
    val publisher = ctx getParam "publisher"
    val subjects = ctx getParam "subjects"
    val binding = ctx getParam "binding"
    val publishDate = ctx getParam "publish-date"
    val overview = ctx getParam "overview"
  
    BookRepo.add(Book(title, author,
                      edition, publisher,
                      subjects, binding,
                      publishDate, overview))
    
    ctx.html("Book has been added!")
  }
I simplified it even more with an infix function
s
Nice! 🙂 Your infix function gave me an idea: What if you tried operator overloading with extension functions to access params like an array? https://kotlinlang.org/docs/reference/operator-overloading.html#indexed I'm thinking about a variation like this:
Copy code
operator fun CtxType.get(name: String): String? {
  val value = this.formParam(name)
  return if (value == "") null else value
}
so you can get the params like this:
Copy code
val title = ctx["title"] ?: return@manual
val author = ctx["author"] ?: return@manual
val edition = ctx["edition"]
val publisher = ctx["publisher"]
\\ etc
Haven't tried it myself, just wanted to share my idea with you in case you like it 🙂
✔️ 1
p
I like operator overloading more than infix function too. Now I think you can put
if (value == "") null else value
to separate extension function too 🙂
o
?: return
is missing on sending back an error html
What I’d do with #ktor (probably javalin has similar mechanism) is define an
IncompleteDataException
type,
?: throw IncompleteDataException(<paramName>)
and install a generic exception handler to return a standard html page. You can reuse it in other routes, of course.
You also might want to return a
Bad Request
status code along with HTML, not
200 OK
as you do now
h
Good idea
Thank you all so much for your ideas.
👍 1