Reputation: 5629
I have the following code which does not work ... not work means in this case it does not persis in database....
DTO / DAO
def createChangelogEntry(changeLog: ChangelogModel): Future[ChangelogModel] = {
println("..........................................")
println(changeLog)
val entry =
(changelogs returning changelogs.map(_.id)
into ((log,id) => log.copy(id=Some(id)))
) += ChangelogModel(None, changeLog.createdat, changeLog.text)
db.run(entry)
}
what could be the problem in this case? match on the model works fine ...
UUpdate:
SQL:
CREATE TABLE Changelog (
id BIGINT(255) NOT NULL,
createdat DATETIME NOT NULL,
text text NOT NULL
)ENGINE=InnoDB DEFAULT CHARSET=utf8;
My Model:
package models
import java.sql.Date
import play.api.libs.json.{JsValue, Json, Writes}
/**
* Created by Felix Hohlwegler on 08.06.2017.
*/
case class ChangelogModel(
id: Option[Int] = None,
createdat: String,
text: String
)
object ChangelogModel {
implicit val changelogFormat = Json.format[ChangelogModel]
}
Controller Function:
package controllers
import javax.inject.{Inject, Singleton}
import dto.changelogDTO
import models.{ChangelogModel, ProcessTemplatesModel}
import play.api.libs.json.{JsError, JsSuccess, Json}
import play.api.mvc.{Action, AnyContent, Controller, Request}
import scala.concurrent.Future
/**
* Created by Felix Hohlwegler on 08.06.2017.
*/
@Singleton
class Changelogs @Inject()(changelogDTO: changelogDTO) extends Controller {
def createChangelogEntry = Action { implicit request =>
request.body.asJson.map(_.validate[ChangelogModel] match {
case JsSuccess(process, _) =>
changelogDTO.createChangelogEntry(process)
case err@JsError(_) => BadRequest("TEST")
case _ => BadRequest("fail to create Counter")
}).getOrElse(BadRequest("Failure tu create Counter"))
Ok("s")
}
}
Upvotes: 0
Views: 120
Reputation: 18187
One problem is that you are not waiting for your insert to complete from your controller:
// Problem
case JsSuccess(process, _) => changelogDTO.createChangelogEntry(process)
You should be mapping on the future and returning its result asynchronously like this:
// Do this
case JsSuccess(process, _) => changelogDTO.createChangelogEntry(process).map(model => Ok(Json.toJson(model))
However this will mean that you will need all of the other cases to return futures too, and you will have to change the resulting action to by async. This is how I would do it:
def createChangelogEntry = Action.async(parse.json) { implicit request =>
request.body.validate[ChangelogModel].fold(
errors => Future(BadRequest(JsError.toJson(errors))),
changelogModel => changelogDTO.createChangelogEntry(changelogModel).map(model => Ok(Json.toJson(model))
)
}
In the meantime you might find it easier to debug by just wrapping your current insert in an Await.result
like this:
import scala.concurrent.duration._
case JsSuccess(process, _) =>
val model = Await.result(changelogDTO.createChangelogEntry(process), 5 seconds)
Ok("We inserted the thing")
Upvotes: 1