1

Using Kotlin and spring data mongodb, I'm trying to find the most idiomatic method that can receive nullable parameters (through user defined filters) and create a MongoTemplate Query with the non-null ones (which, in Java, would be a bunch of ifs). This is what I came up with, so far, but I wonder if there's a better way:

// extending Query
open class Filter {
  // case insensitive 'like' criteria
  fun Query.like(field: String, value: String?) = value?.let {
    this.addCriteria(Criteria.where(field).regex(it,"i"))
  }

  // queries from a date, to a date or between two dates
  fun <T: Comparable<T>> Query.between(field: String, from: T?, to: T?) {
    if (from != null || to != null) {
      val criteria = where(field)
      from?.let { criteria.gte(it) }
      to?.let { criteria.lte(it) }
      this.addCriteria(criteria)
    }
  }

  fun Query.onlyActive(active: Boolean?) = when (active) {
    true -> this.addCriteria(Criteria.where("active").`is`(true))
    else -> null
  }
}

// data class extending Filter()
data class myFilter(val: name: String, val type: String?, val content:String?,
  val fromNum: Int?, val toNum: Int?, val fromDate: LocalDateTime?,
  val toDate: LocalDateTime?, val active? = false): Filter() {

  fun toQuery(): Query {
    // name is a mandatory param
    val query = Query.query(Criteria.where("name").`is`(name))

    with(query) {
      like("type", type)
      like("content", content)
      between("num", fromNum, toNum)
      between("date", fromDate, toDate)
      onlyActive(active)
    }

    return query
  }
}
Tarek
  • 3,080
  • 5
  • 38
  • 54

0 Answers0