playframwork控制器返回创建对象的ID [英] playframwork controller return ID of created object
本文介绍了playframwork控制器返回创建对象的ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在我的scala playframework应用程序中,我想返回我创建的项目的ID.
in my scala playframework application I want to return the ID of the project I created.
控制器代码
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"
what would be a best preactise to the ID instead of return "OK"
谢谢
错误
新错误
新品
再次
推荐答案
类似的事情(这将返回JSON对象).您也可以将整个客户端作为JSON对象返回.另外,在这种情况下,使用HTTP 201(创建)是更正确的响应.
Something like this (this will return a JSON object). You can also potentially return the whole client as a JSON object. Also, HTTP 201 (created) is a more correct response to use in this case.
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"))
}
}
这篇关于playframwork控制器返回创建对象的ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文