play framework controller return 创建对象的ID
playframwork controller return ID of created object
在我的 scala playframework 应用程序中,我想 return 我创建的项目的 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 的最佳预演而不是 return "OK"
谢谢
错误
新错误
新的
再来一张
类似这样的东西(这将 return 一个 JSON 对象)。您还可以 return 整个客户端作为 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"))
}
}
在我的 scala playframework 应用程序中,我想 return 我创建的项目的 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 的最佳预演而不是 return "OK"
谢谢
错误
新错误
新的
再来一张
类似这样的东西(这将 return 一个 JSON 对象)。您还可以 return 整个客户端作为 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"))
}
}