Felix
Felix

Reputation: 5629

playframwork controller return ID of created object

in my scala playframework application I want to return the ID of the project I created.

controller code

  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 Code

  /**
    * 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)
  }

what would be a best preactise to the ID instead of return "OK"

thanks

ERROR enter image description here

New Error enter image description here

New Ones enter image description here

Again one enter image description here

Upvotes: 0

Views: 66

Answers (1)

sheunis
sheunis

Reputation: 1544

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"))
  }
}

Upvotes: 1

Related Questions