api/customer

This commit is contained in:
Bossanyi Tibor
2020-05-03 21:02:57 +02:00
parent 12376fb9bf
commit ce499986b2
14 changed files with 482 additions and 0 deletions
@@ -0,0 +1,12 @@
package com.aitrainer.api
import org.springframework.boot.SpringApplication
import org.springframework.boot.autoconfigure.SpringBootApplication
@SpringBootApplication
class ApiApplication {
}
fun main(args: Array<String>) {
SpringApplication.run(ApiApplication::class.java, *args)
}
@@ -0,0 +1,44 @@
package com.aitrainer.api.controller
import com.aitrainer.api.model.Customer
import com.aitrainer.api.repository.CustomerRepository
import org.springframework.http.HttpStatus
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.*
import java.util.*
import javax.validation.Valid
@RestController
@RequestMapping("/api")
class CustomerController ( private val customerRepository: CustomerRepository ) {
@GetMapping("/customers")
fun getAllCustomers(): List<Customer> =
customerRepository.findAll()
@PostMapping("/customers")
fun createNewArticle(@Valid @RequestBody customer: Customer): Customer =
customerRepository.save(customer)
@GetMapping("/customers/{id}")
fun getCustomerById(@PathVariable(value = "id") customerId: Long): ResponseEntity<Customer> {
return customerRepository.findById(customerId).map { customer ->
ResponseEntity.ok(customer)
}.orElse(ResponseEntity.notFound().build())
}
@PutMapping("/customers/{id}")
fun updateCustomerById(@PathVariable(value = "id") customerId: Long,
@Valid @RequestBody newCustomer: Customer): ResponseEntity<Customer> {
return customerRepository.findById(customerId).map { existingCustomer ->
val updatedCustomer: Customer = existingCustomer
.copy(name = newCustomer.name,
firstname = newCustomer.firstname,
sex = newCustomer.sex,
age = newCustomer.age)
ResponseEntity.ok().body(customerRepository.save(updatedCustomer))
}.orElse(ResponseEntity.notFound().build())
}
}
@@ -0,0 +1,6 @@
package com.aitrainer.api.enums
enum class SexEnum (val sex: String) {
MAN ("m"),
WOMAN("w")
}
@@ -0,0 +1,23 @@
package com.aitrainer.api.model
import com.aitrainer.api.enums.SexEnum
import javax.persistence.Entity
import javax.persistence.GeneratedValue
import javax.persistence.GenerationType
import javax.persistence.Id
import javax.validation.constraints.NotBlank
@Entity
data class Customer (
@get: NotBlank
val name: String = "",
val firstname: String,
val email: String,
val age: Int,
val sex: String,
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
val customer_id: Long? = null
)
@@ -0,0 +1,8 @@
package com.aitrainer.api.repository
import com.aitrainer.api.model.Customer
import org.springframework.data.jpa.repository.JpaRepository
import org.springframework.stereotype.Repository
@Repository
interface CustomerRepository : JpaRepository<Customer, Long>