Skip to content

Instantly share code, notes, and snippets.

@chrissearle
Last active January 5, 2022 13:37
Show Gist options
  • Save chrissearle/c825464fc58e8e883ff7d0e2eda85021 to your computer and use it in GitHub Desktop.
Save chrissearle/c825464fc58e8e883ff7d0e2eda85021 to your computer and use it in GitHub Desktop.
Kotlin coroutine spring boot MVC - Controller vs DSL
@RestController
class Controller(val service: SomeService) {
@GetMapping("/something")
fun all() = service.all()
@PostMapping("/something")
suspend fun save(@RequestBody something: CreateDTO) = service.create(something)
@PutMapping("/something/{id}")
suspend fun update(@PathVariable id: Long, @RequestBody updates: UpdateDTO) = service.update(id, updates)
}
@Configuration
class RouterConfiguration {
@Bean
fun routes(handler: SomethingHandler) = coRouter {
"/something".nest {
GET("", handler::all)
POST("", handler::create)
PUT("/{id}", handler::update)
}
}
}
@Component
class SomethingHandler(private val service : SomethingService) {
suspend fun all(req: ServerRequest) = ok().bodyAndAwait(this.service.all())
suspend fun create(req: ServerRequest): ServerResponse {
val body = req.awaitBody<CreateDTO>()
val something = this.service.create(body)
return created(URI.create("/somehting/${something.id}")).buildAndAwait()
}
suspend fun update(req: ServerRequest): ServerResponse {
val body = req.awaitBody<UpdateDTO>()
val something = service.update(req.pathVariable("id").toLong(), body)
return when {
something != null -> {
noContent().buildAndAwait()
}
else -> notFound().buildAndAwait()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment