Skip to content

Commit f2df155

Browse files
vjames19jknack
authored andcommitted
using reified types to extract param, header and body. (#816)
* using reified types to extract param, header and body. * Added some examples.
1 parent 384b93f commit f2df155

File tree

2 files changed

+41
-0
lines changed
  • modules/jooby-lang-kotlin/src

2 files changed

+41
-0
lines changed

modules/jooby-lang-kotlin/src/main/kotlin/org/jooby/Jooby.kt

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -305,14 +305,26 @@ val Mutant.doubleValue: Double
305305
val Mutant.value: String
306306
get() = value()
307307

308+
inline fun <reified T> Mutant.to(): T {
309+
return this.to(T::class.java)
310+
}
311+
308312
fun <T:Any> Mutant.to(type: KClass<T>): T {
309313
return this.to(type.java)
310314
}
311315

316+
inline fun <reified T> Mutant.to(contentType: MediaType): T {
317+
return this.to(T::class.java, contentType)
318+
}
319+
312320
fun <T:Any> Mutant.to(type: KClass<T>, contentType: MediaType): T {
313321
return this.to(type.java, contentType)
314322
}
315323

324+
inline fun <reified T> Mutant.to(contentType: String): T {
325+
return this.to(T::class.java, contentType)
326+
}
327+
316328
fun <T:Any> Mutant.to(type: KClass<T>, contentType: String): T {
317329
return this.to(type.java, contentType)
318330
}
@@ -341,3 +353,15 @@ fun <T:Comparable<T>> Mutant.toSortedSet(type: KClass<T>): SortedSet<T> {
341353
fun <T:Any> Request.set(type: KClass<T>, value: Any): Request {
342354
return this.set(type.java, value)
343355
}
356+
357+
inline fun <reified T> Request.param(name: String): T {
358+
return param(name).to(T::class.java)
359+
}
360+
361+
inline fun <reified T> Request.header(name: String): T {
362+
return param(name).to(T::class.java)
363+
}
364+
365+
inline fun <reified T> Request.body(): T {
366+
return body().to(T::class.java)
367+
}

modules/jooby-lang-kotlin/src/test/kotlin/examples/kotlin/Fn.kt

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,5 +39,22 @@ fun main(args: Array<String>) {
3939
chain.next(req, rsp)
4040
}
4141
}.name("pets")
42+
43+
get("/params") {
44+
val name = param<String>("name")
45+
val age = param<Int>("age")
46+
"Hi $name, your username is now ${name + age}"
47+
}
48+
49+
get("/headers") {
50+
val name = header<String>("name")
51+
val age = header<Int>("age")
52+
"Hi $name, your username is now ${name + age}"
53+
}
54+
55+
get("/body") {
56+
val user = body<User>()
57+
user
58+
}
4259
}
4360
}

0 commit comments

Comments
 (0)