From 9ddf86453aa29059415cf2ad4ce684a798071807 Mon Sep 17 00:00:00 2001 From: Muhammad Khubaib Imtiaz <18.bscs.803@gmail.com> Date: Fri, 21 Jun 2024 08:49:36 +0500 Subject: [PATCH] -Multiple Products Endpoint Imp (#186) --- .../repository/product/ProductRepository.kt | 6 +++++ src/main/kotlin/com/example/plugins/Routes.kt | 25 +++++++++++++++++++ 2 files changed, 31 insertions(+) diff --git a/src/main/kotlin/com/example/domain/repository/product/ProductRepository.kt b/src/main/kotlin/com/example/domain/repository/product/ProductRepository.kt index 1ead137..b1a8b0f 100644 --- a/src/main/kotlin/com/example/domain/repository/product/ProductRepository.kt +++ b/src/main/kotlin/com/example/domain/repository/product/ProductRepository.kt @@ -69,6 +69,12 @@ class ProductRepository : ProductDao { } } + suspend fun getProductsByMultipleIds(ids: List): List? { + return DatabaseFactory.dbQuery { + ProductTable.select { ProductTable.id inList ids } + .mapNotNull { rowToResult(it) } + } + } override suspend fun getAllProducts(): List? { return DatabaseFactory.dbQuery { diff --git a/src/main/kotlin/com/example/plugins/Routes.kt b/src/main/kotlin/com/example/plugins/Routes.kt index b74b587..2e1ced6 100644 --- a/src/main/kotlin/com/example/plugins/Routes.kt +++ b/src/main/kotlin/com/example/plugins/Routes.kt @@ -1098,6 +1098,31 @@ fun Route.products( } } + get("v1/products/multiple") { + val idsString = call.request.queryParameters["ids"] + if (idsString.isNullOrBlank()) { + call.respond(HttpStatusCode.BadRequest, "No product IDs provided") + return@get + } + + val ids = idsString.split(",").mapNotNull { it.toLongOrNull() } + if (ids.isEmpty()) { + call.respond(HttpStatusCode.BadRequest, "Invalid product IDs provided") + return@get + } + + try { + val products = db.getProductsByMultipleIds(ids) + if (products.isNullOrEmpty()) { + call.respond(HttpStatusCode.NotFound, "No products found for the provided IDs") + } else { + call.respond(HttpStatusCode.OK, products) + } + } catch (e: Exception) { + call.respond(HttpStatusCode.InternalServerError, "Error while fetching products: ${e.message}") + } + } + put("v1/products/{id}") { val id = call.parameters["id"]?.toLongOrNull() ?: return@put call.respondText( text = "Invalid or Missing Product ID",