add create product api-endpoint

This commit is contained in:
Denis Savosin
2024-09-27 18:48:16 +07:00
parent 7840146b80
commit 2b07944b0e
4 changed files with 40 additions and 7 deletions

View File

@@ -1,11 +1,14 @@
package com.example.demo.controllers
import com.example.demo.exceptions.NotFoundException
import com.example.demo.models.Product
import com.example.demo.provider.ProductRepository
import com.example.demo.requests.CreateProductRequest
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.encodeToJsonElement
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.web.bind.annotation.*
import java.time.OffsetDateTime
import java.util.*
@RestController
@@ -22,4 +25,26 @@ class ProductController(
return Json.encodeToJsonElement(value = product).toString()
}
@PostMapping(value = [""], consumes = ["application/json"], produces = ["application/json"])
@ResponseBody
fun createProduct(
@RequestBody product: CreateProductRequest
): String {
val productModel = Product(
id = null,
guid = UUID.randomUUID(),
name = product.name,
description = product.description,
price = product.price,
createdAt = OffsetDateTime.now(),
updatedAt = null,
)
val saved = productRepository.save(productModel)
return Json.encodeToJsonElement(value = saved).toString()
}
// todo delete with soft-delete
}

View File

@@ -4,9 +4,9 @@ package com.example.demo.models
import com.example.demo.models.serializables.OffsetDateTimeSerialization
import com.example.demo.models.serializables.UuidSerialization
import com.example.demo.utils.roundTo
import jakarta.persistence.Column
import jakarta.persistence.Id
import kotlinx.serialization.Serializable
import org.springframework.data.annotation.Id
import org.springframework.data.relational.core.mapping.Column
import org.springframework.data.relational.core.mapping.Table
import java.time.OffsetDateTime
import java.util.*
@@ -14,17 +14,18 @@ import java.util.*
@Table(value = "product", schema = "public")
@Serializable
data class Product(
@Id var id: Long,
@Id
val id: Long?,
@Serializable(with = UuidSerialization::class)
val guid: UUID,
val name: String,
val description: String?,
val price: Int,
val price: Long,
@Serializable(with = OffsetDateTimeSerialization::class)
@Column(name = "created_at")
@Column(value = "created_at")
val createdAt: OffsetDateTime,
@Serializable(with = OffsetDateTimeSerialization::class)
@Column(name = "updated_at")
@Column(value = "updated_at")
val updatedAt: OffsetDateTime?,
) {
fun getPriceDouble(): Double = (price.toDouble() / 100).roundTo(2)

View File

@@ -38,7 +38,7 @@ class MockedShopProvider: ShopProvider {
guid = UUID.randomUUID(),
name = name,
description = null,
price = (price * 100).toInt(),
price = (price * 100).toLong(),
createdAt = OffsetDateTime.now(),
updatedAt = null,
)

View File

@@ -0,0 +1,7 @@
package com.example.demo.requests
data class CreateProductRequest(
val name: String,
val description: String?,
val price: Long,
)