Skip to content

Instantly share code, notes, and snippets.

@theboreddev
Created December 21, 2022 07:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save theboreddev/4212cfef120d2571efb601ecfd6b6797 to your computer and use it in GitHub Desktop.
Save theboreddev/4212cfef120d2571efb601ecfd6b6797 to your computer and use it in GitHub Desktop.
package com.theboreddev.springbootapp
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.beans.factory.annotation.Value
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.*
import org.springframework.web.util.UriComponentsBuilder
@RestController
@RequestMapping("/api/customers")
class CustomerController(@Autowired val repository: CustomersRepository) {
@PostMapping
fun createCustomer(@RequestBody customer: Customer, uriBuilder: UriComponentsBuilder): ResponseEntity<String> {
return repository.create(customer)
.onSuccessDo { e ->
ResponseEntity
.created(uriBuilder
.path("/api/customers/{id})")
.buildAndExpand(e.entity().id)
.toUri()
).build()
}.response() as ResponseEntity<String>
}
@GetMapping("/{id}")
fun findCustomer(@PathVariable("id") id: Long): ResponseEntity<Customer> {
return repository.findById(id)
.onFailureDo { e ->
when (e.exception()) {
is CustomerNotFound -> ResponseEntity.notFound().build()
else -> ResponseEntity.internalServerError().build()
}
}.response() as ResponseEntity<Customer>
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment