1

I am using Ktor to set up a small API. I am also using Exposed for database operations.

I want to select from the database using inList but only for columns that show up in the queryParameters. Here's how things look so far:

Routes.kt

fun Route.purchaseRouting() {
    route("/purchases") {
        get {
            val params = call.request.queryParameters.toMap()
            val purchases = purchasesDAO.allPurchases(params)
            call.respond(purchases)
        }
    }
}

PurchasesDAO.kt:

override suspend fun allPurchases(params: Map<String, List<String>>): List<Purchase> = DatabaseFactory.dbQuery {
    val ids = params["id"].map { it.toInt() }
    val amounts = params["location"]
    // There are a couple more params but just including these for the concept.

    // Select the correct correct rows from the DB, convert them to purchase objects, and return.
    Purchases.select {
        Purchases.location inList locations!! and Purchases.dates inList dates!!
    }.map(::resultRowToPurchase)
}

This will only work if both location and date are in the queryParameters. But how do I go about only filtering with them only if they exist? For just two parameters it is easy, but I have more columns that I didn't include here. I wish to do this dynamically, if possible.

Spencer Stith
  • 31
  • 1
  • 4
  • There are actually many different approaches discussed in SO under different questions. Some examples: https://stackoverflow.com/questions/52531094/how-to-add-multiple-filter-conditions-based-on-incoming-parameters-to-the-expose and https://stackoverflow.com/questions/54361503/how-to-add-multiple-or-filter-conditions-based-on-incoming-parameters-using-expo – Tarmo Sep 23 '22 at 18:22
  • Thank you for the reply! I have seen these questions in my searches and I am having trouble finding how to apply them to my situation. In those questions, they knew they would be receiving said parameters, which I know how to do pretty easily. In my situation, I never know which parameters may exist in `queryParameters`. It could be none or all 7. – Spencer Stith Sep 23 '22 at 19:22
  • No they didn't know. Take this one for example https://stackoverflow.com/a/54376775/3020903. The part `for((k, v) in params) {` implies that there can be any number of params and this is not fixed and no matter which of them client happens to use, the query adapts. Only thing you need to know is what are the possibilities for parameters. – Tarmo Sep 24 '22 at 12:46

0 Answers0