Last active
January 5, 2022 13:37
-
-
Save chrissearle/c825464fc58e8e883ff7d0e2eda85021 to your computer and use it in GitHub Desktop.
Kotlin coroutine spring boot MVC - Controller vs DSL
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
@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) | |
} |
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
@Configuration | |
class RouterConfiguration { | |
@Bean | |
fun routes(handler: SomethingHandler) = coRouter { | |
"/something".nest { | |
GET("", handler::all) | |
POST("", handler::create) | |
PUT("/{id}", handler::update) | |
} | |
} | |
} |
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
@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