Play 2.1, Slick and JSON
As an exercise in familiarizing myself with Play Framework 2.x Scala, I am implementing a lightweight CMS for a dynamic corporate website.
I was curious about what the new 2.x release offers with regards to JSON reads and writes as well as Slick for data access.
In this post, I'll present some code detailing how I used Slick and the new macro enabled JSON utilities in Play 2.1 in order to implement a simple CMS.
I prefer to use a case class as a parameter to Slick's table object, as opposed to tuples, as the case class will lead to trivial JSON read/writes later on.
I use case classes to provide different representations of the base model for the CMS: Article
The above case class represents the complete model (all colums in the database table). The class Article is the parameter to the table:
~ is a projection operator. It is a member of the class Column.
Here are some examples of basic CRUD with Slick. In these examples, I am making use of the various other case classes even though Article is still the class mapped to the Table class
In Slick, you describe the "Projection" (a set of table rows and columns) you wish to query or update by passing a Column projection using ~ to map(). This is equivalent the SELECT in SQL
Describe the particular rows you are interested in with filter(). This is equivalent to WHERE in SQL
As you can see, we are making use of scala's Try[T] introduced in Scala 2.10 and pattern matching from the calling code:
Reading from a JSON request is pretty simple, done the ArticleCreate implicit, the Play macro takes care of the rest. json.validate() takes the implicit and returns the monadic JsResult[T]
I'm also making use of a sealed trait as an enum:
In this case I need to include the implicit conversion:
I'm still figuring a lot of this stuff out, and I'm sure I've missed much, but getting a JSON request into the DB seemed pretty straightforward!