Play + Slick: how to make partial model updates?

I am using Play 2.2.x with Slick 2.0 (with the MYSQL backend) to write a REST API. I have a model Userwith a bunch of types of fields age, name, genderetc. I want to create a route PATCH /users/:idthat accepts a partial user object (i.e., a subset of the fields of the full user model) in the body and updates the user information. I am confused how I can achieve this:

  • How to use the PATCHverb in Play 2.2.x?
  • What is the general way to parse a partial user object in an update request for execution in Slick 2.0? I expect one SQL statement to execute, for example.update users set age=?, dob=? where id=?
+4
source share
1 answer

Disclaimer: I did not use Slick, so I just went to their Plain SQL Queries documentation for this.

To answer your first question:

PATCHis just another HTTP verb in your file routes, so for your example:

PATCH       /users/:id          controllers.UserController.patchById(id)

Yours UserControllercould be something like this:

val possibleUserFields = Seq("firstName", "middleName", "lastName", "age")

def patchById(id:String) = Action(parse.json) { request =>

  def addClause(fieldName:String) = {
    (request.body \ fieldName).asOpt[String].map { fieldValue =>
      s"$fieldName=$fieldValue"
    }
  }

  val clauses = possibleUserFields.flatMap ( addClause )

  val updateStatement = "update users set " + clauses.mkString(",") + s" where id = $id"

  // TODO: Actually make the Slick call, possibly using the 'sqlu' interpolator (see docs)
  Ok(s"$updateStatement")
}

What does it do:

  • Defines a list of JSON field names that may be present in PATCHJSON

  • Defines an action that will parse the incoming body as JSON

  • Iterates over all possible field names, checking if they exist in the incoming JSON

  • If so, add a form clause fieldname=<newValue>to the list

  • SQL,

, , , ( Slick) Slick, , , Slick, : -)

0

Source: https://habr.com/ru/post/1526460/


All Articles