在我的scala playframework应用程序中,我想返回我创建的项目的ID。
控制器代码
def createClient = Action { implicit request =>
request.body.asJson.map(_.validate[ClientModel] match {
case JsSuccess(client, _) =>
clientDTO.createClient(client).map{
case cnt => println(cnt)
case _ => println("Fehler")
}
case err@JsError(_) => BadRequest("TEST")
case _ => BadRequest("fail to create Counter")
}).getOrElse(BadRequest("Failure tu create Counter"))
Ok("s")
}
DTO代码
/**
* Insert Query for a new Client
*/
val insertClientQuery = clients returning clients.map(_.id) into ((client, id) => client.copy(id = Some(id)))
/**
* Creates a new client
*
* @param client Client Model
* @return
*/
def createClient(client: ClientModel): Future[ClientModel] = {
val action = insertClientQuery += client
db.run(action)
}
什么是ID的最佳预设,而不是返回" OK"
感谢
答案 0 :(得分:1)
这样的东西(这会返回一个JSON对象)。您还可以将整个客户端作为JSON对象返回。此外,HTTP 201(已创建)是在这种情况下使用的更正确的响应。
def createClient = Action.async { implicit request =>
request.body.asJson.map(_.validate[ClientModel]) match {
case c: JsSuccess[ClientModel] =>
clientDTO.createClient(c.get).map{
cnt => Created(Json.obj("id" -> cnt.id))
}.recover {
case e: Exception => BadRequest("Could not create client")
}
case err: JsError => Future.successful(BadRequest("TEST"))
}
}