【问题标题】:playframwork controller return ID of created object播放框架控制器返回创建对象的 ID
【发布时间】:2017-07-31 16:51:34
【问题描述】:

在我的 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”

谢谢

错误

新错误

新的

再来一个

【问题讨论】:

    标签: scala playframework playframework-2.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"))
      }
    }
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多