Created
September 5, 2018 03:31
-
-
Save thiagotn/bdb2e03620b1983f45ab64463cb82c4c to your computer and use it in GitHub Desktop.
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
package com.example.demoapi.products | |
import org.springframework.http.ResponseEntity | |
import org.springframework.web.bind.annotation.* | |
import org.springframework.web.servlet.support.ServletUriComponentsBuilder | |
import java.net.URI | |
@RequestMapping("/products") | |
@RestController | |
class ProductsController(private val service: ProductsService) { | |
@PostMapping | |
fun create(@RequestBody product: Product): ResponseEntity<Any> { | |
val created = service.create(product) | |
return ResponseEntity.created(buildURI(created.id)).build() | |
} | |
@GetMapping() | |
fun list(): ResponseEntity<Any> { | |
return ResponseEntity.ok(service.list()) | |
} | |
@GetMapping("/{id}") | |
fun read(@PathVariable id: Int): ResponseEntity<Any> { | |
val product = service.read(id) ?: return ResponseEntity.notFound().build<Any>() | |
return ResponseEntity.ok(product) | |
} | |
@PatchMapping() | |
fun update(@RequestBody product: Product): ResponseEntity<Any> { | |
val updated = service.update(product) ?: return ResponseEntity.notFound().build<Any>() | |
return ResponseEntity.ok(updated) | |
} | |
@DeleteMapping("/{id}") | |
fun delete(@PathVariable id: String): ResponseEntity<Any> { | |
service.delete(id) | |
return ResponseEntity.ok().build() | |
} | |
private fun buildURI(id: Int):URI = ServletUriComponentsBuilder | |
.fromCurrentRequest() | |
.path("/{id}") | |
.buildAndExpand(id) | |
.toUri() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment