override fun handleRequest()

in software/src/main/kotlin/com/amazonaws/sample/PutProductHandler.kt [27:83]


    override fun handleRequest(event: APIGatewayV2HTTPEvent, context: Context): APIGatewayV2HTTPResponse {
        val logger = context.logger
        logger.log(event.toString())

        val id = event.pathParameters?.get("id") ?: return missingId()

        if (event.body == null || event.body.isEmpty()) {
            return APIGatewayV2HTTPResponse().apply {
                statusCode = 400
                headers = mapOf("Content-Type" to "application/json")
                body = """{"message": "Empty request body"}"""
            }
        }

        val product = try {
            Json.decodeFromString<Product>(event.body)
        } catch (e: Exception) {
            logger.log(e.message)
            return APIGatewayV2HTTPResponse().apply {
                statusCode = 400
                headers = mapOf("Content-Type" to "application/json")
                body = """{"message": "Failed to parse product from request body"}"""
            }
        }

        logger.log("Product: $product")

        if (id != product.id) {
            logger.log("ERROR: Product ID in path ($id) does not match product ID in body (${product.id})")
            return APIGatewayV2HTTPResponse().apply {
                statusCode = 400
                headers = mapOf("Content-Type" to "application/json")
                body = """{"message": "Product ID in path does not match product ID in body"}"""
            }
        }

        val itemValues = mapOf(
            "PK" to AttributeValue.S(product.id),
            "name" to AttributeValue.S(product.name),
            "price" to AttributeValue.N(product.price.toString())
        )

        runBlocking {
            dynamoDbClient.putItem(
                PutItemRequest {
                    tableName = productTable
                    item = itemValues
                }
            )
        }

        return APIGatewayV2HTTPResponse().apply {
            statusCode = 201
            headers = mapOf("Content-Type" to "application/json")
            body = """{"message": "Product created"}"""
        }
    }