Decluttering the GAE Datastore API with Scala

Working with the Google App Engine Query API means a lot of boilerplate code. In Java there is no way around it.

Here is what a really simple query looks like:

Query q = new Query("Work").setFilter(
  CompositeFilterOperator.and(
    new FilterPredicate("c", FilterOperator.EQUAL, work.c),
    new FilterPredicate("m", FilterOperator.EQUAL, work.m),
    new FilterPredicate("digitPos", FilterOperator.EQUAL, work.digitPos)
  )
)

Fortunately in Scala we can remove the clutter by adding imports and defining an implicit conversion:

import FilterOperator._
import CompositeFilterOperator._

implicit def tuple2FilterPredicate(x: (String, FilterOperator, Any)): FilterPredicate = {
  new FilterPredicate(x._1, x._2, x._3)
}

Which makes the API look much more like MongoDB :)

val q = new Query("Work").setFilter {
  and (
    ("c", EQUAL, work.c),
    ("m", EQUAL, work.m),
    ("digitPos", EQUAL, work.digitPos)
  )
}


Β© 2017. All rights reserved.

Powered by Hydejack v6.6.1