71 lines
2.1 KiB
Kotlin
71 lines
2.1 KiB
Kotlin
package com.example.customerapi
|
|
|
|
import org.springframework.beans.factory.annotation.Autowired
|
|
import org.springframework.boot.CommandLineRunner
|
|
import org.springframework.boot.autoconfigure.SpringBootApplication
|
|
import org.springframework.boot.runApplication
|
|
import org.springframework.data.annotation.Id
|
|
import org.springframework.data.mongodb.core.mapping.Document
|
|
import org.springframework.data.mongodb.repository.MongoRepository
|
|
import org.springframework.stereotype.Repository
|
|
import org.springframework.web.bind.annotation.GetMapping
|
|
import org.springframework.web.bind.annotation.RequestMapping
|
|
import org.springframework.web.bind.annotation.RestController
|
|
import java.io.Serializable
|
|
import kotlin.random.Random
|
|
|
|
@SpringBootApplication
|
|
class CustomerApiApplication @Autowired constructor(
|
|
private val customerRepository: CustomerRepository,
|
|
) : CommandLineRunner {
|
|
override fun run(vararg args: String?) {
|
|
|
|
val customer = Customer.create("Sambo - ${Random.nextInt(1000)}", "Chea - ${Random.nextInt(1000)}")
|
|
|
|
val saved = customerRepository.save(customer)
|
|
|
|
println(saved)
|
|
}
|
|
}
|
|
|
|
fun main(args: Array<String>) {
|
|
runApplication<CustomerApiApplication>(*args)
|
|
}
|
|
|
|
|
|
@Document
|
|
data class Customer(
|
|
@Id
|
|
val id: String? = null,
|
|
var firstName: String,
|
|
var lastName: String,
|
|
) : Serializable {
|
|
companion object {
|
|
fun create(
|
|
firstName: String,
|
|
lastName: String
|
|
): Customer {
|
|
return Customer(null, firstName, lastName)
|
|
}
|
|
}
|
|
}
|
|
|
|
@Repository
|
|
interface CustomerRepository : MongoRepository<Customer, String>
|
|
|
|
@RestController
|
|
@RequestMapping("/customers")
|
|
class CustomerController @Autowired constructor(
|
|
private val customerRepository: CustomerRepository
|
|
) {
|
|
@GetMapping
|
|
fun getAllCustomers(): Collection<Customer> {
|
|
return customerRepository.findAll()
|
|
}
|
|
|
|
@GetMapping("/create")
|
|
fun createCustomer(): Customer? {
|
|
val customer = Customer.create("Sambo - ${Random.nextInt(1000)}", "Chea - ${Random.nextInt(1000)}")
|
|
return customerRepository.save(customer)
|
|
}
|
|
} |