Note that there are some explanatory texts on larger screens.

plurals
  1. POOptional Json Body Parser
    text
    copied!<p>I'm trying to write a DRY CRUD restful service using PlayFramework. Here's the code for it. </p> <pre><code>def crudUsers(operation: String) = Action(parse.json) { request =&gt; (request.body).asOpt[User].map { jsonUser =&gt; try { DBGlobal.db.withTransaction { val queryResult = operation match { case "create" =&gt; UsersTable.forInsert.insertAll(jsonUser) Json.generate(Map("status" -&gt; "Success", "message" -&gt; "Account inserted")) case "update" =&gt; val updateQ = UsersTable.where(_.email === jsonUser.email.bind).map(_.forInsert) println(updateQ.selectStatement) updateQ.update(jsonUser) Json.generate(Map("status" -&gt; "Success", "message" -&gt; "Account updated")) case "retrieve" =&gt; val retrieveQ = for(r &lt;- UsersTable) yield r println(retrieveQ.selectStatement) Json.generate(retrieveQ.list) case "delete" =&gt; val deleteQ = UsersTable.where(_.email === jsonUser.email) deleteQ.delete Json.generate(Map("status" -&gt; "Success", "message" -&gt; "Account deleted")) } Ok(queryResult) } } catch { case _ =&gt; val errMsg: String = operation + " error" BadRequest(Json.generate(Map("status" -&gt; "Error", "message" -&gt; errMsg))) } }.getOrElse(BadRequest(Json.generate(Map("status" -&gt; "Error", "message" -&gt; "error")))) </code></pre> <p>} }</p> <p>I've noticed that update, delete and create operations work nicely. However the retrieve operation fails with <code>For request 'GET /1/users' [Invalid Json]</code>. I'm pretty sure this is because the JSON parser is not tolerant of a GET request with no JSON passed in the body.</p> <p>Is there a way to special case the GET/Retrieve operation without losing losing the DRY approach I've started here? </p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload