Skip to content

Instantly share code, notes, and snippets.

@krishnabhargav
Created October 2, 2019 23:04
Show Gist options
  • Save krishnabhargav/6b38159021d1804ac3839f4049728cf7 to your computer and use it in GitHub Desktop.
Save krishnabhargav/6b38159021d1804ac3839f4049728cf7 to your computer and use it in GitHub Desktop.
import infrastructure.Json
import io.javalin.Javalin
import io.javalin.http.Context
import io.javalin.http.HandlerType
import io.javalin.plugin.json.FromJsonMapper
import io.javalin.plugin.json.JavalinJson
import io.javalin.plugin.json.ToJsonMapper
fun main() {
val app: Javalin = Javalin.create().start(7000)
JavalinJson.toJsonMapper = object : ToJsonMapper {
override fun map(obj: Any): String = Json.toJson(obj)
}
JavalinJson.fromJsonMapper = object : FromJsonMapper {
override fun <T> map(json: String, targetClass: Class<T>): T = Json.fromJsonWithClass(json, targetClass)
}
app.get("/") { ctx ->
ctx.result("Hello, World!")
}
app.exception(Exception::class.java) { e, ctx ->
e.printStackTrace()
}
app.register(EmployeeController())
}
fun String.makeHandlerPath() : String = this.replace("//","/").trim().removeSuffix("/")
fun <T : Any> Javalin.register(controller:T) {
val kClass = controller.javaClass
val controllerPath = (kClass.annotations.first { it is Root } as Root).value
//lets get actions
kClass.declaredMethods.forEach {
when (val annotation = it.annotations.firstOrNull()) {
is Get -> {
val x = annotation.value
val handlerPath = "$controllerPath/$x".makeHandlerPath()
println("Registering path = $handlerPath")
this.addHandler(HandlerType.GET,
handlerPath) { ctx -> it.invoke(controller,ctx)}
}
is Post -> this.addHandler(HandlerType.POST,
"$controllerPath/$annotation.value".makeHandlerPath()) { ctx -> it.invoke(ctx)}
}
}
}
annotation class Get(val value: String="")
annotation class Post(val value: String)
annotation class Root(val value: String)
@Root("/employee")
class EmployeeController {
sealed class Device {
data class Laptop(val model: String) : Device()
data class Phone(val model: String, val carrier: String) : Device()
}
class Employee(val id: Int, val device: List<Device>)
private val employees = listOf(
Employee(1, listOf(Device.Laptop("Macbook Pro"), Device.Phone("IPhone", "T-Mobile"))),
Employee(2, listOf(Device.Laptop("Macbook Pro"), Device.Phone("IPhone", "T-Mobile")))
)
@Get()
fun allEmployees(ctx : Context) {
ctx.json(employees)
}
@Get("/:id")
fun byId(ctx:Context) {
val result = when(ctx.pathParam("id").toInt()){
1 -> employees[0]
2 -> employees[1]
else -> throw Exception("Invalid id")
}
ctx.json(result)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment