LoginSignup
2
0

More than 5 years have passed since last update.

playframeworkでのJsonRequestの色々

Posted at

PlayScalaでJsonRequestを受けた際の色々メモ

最終的には↓みたいにした。

sample1.scala
package com.example.common

import play.api.mvc._
import play.api.libs.json._
import scala.concurrent.Future

abstract class JsonValidatedController(cc: ControllerComponents) extends AbstractController(cc) {

  def async[A](request: Request[AnyContent])(async: A => Result)(implicit reads: Reads[A]) = {

    Future.successful {
      val json = request.body.asJson.map(_.validate(reads))
      json match {
        case Some(s: JsSuccess[A]) => async(s.get)
        case Some(e: JsError) => BadRequest(JsError.toJson(e))
        case None => UnsupportedMediaType
      }
    }
  }
}

BodyParserにjsonを渡すパターン

sample2.scala
package com.example.common

import play.api.mvc._
import play.api.libs.json._
import scala.concurrent.Future

abstract class JsonValidatedController(cc: ControllerComponents) extends AbstractController(cc) {

  def async[A](request: Request[JsValue])(async: A => Result)(implicit reads: Reads[A]) = {

    Future.successful {
      val json = request.body.validate(reads).asEither
      json match {
        case Right(s) => async(s)
        case Left(e => BadRequest(JsError.toJson(e))
      }
    }
  }
}

呼び出し時に以下のようにする。

Action(parser.json) {
  ...
}

シンプルになるが、ContentTypeがJsonではない場合、デフォルトエラーページが返る。
→いついかなるときもJsonでレスポンス返したいのでボツ
CustomErrorHandlerを定義しても動かなかった。
→コンパイルDIしてるせいかも?

parser.json[任意の型]のパターン

こうやってAction呼び出すと、ハナからRequest[任意の型]で受けれた。

Action(parser.json[任意の型]) {
  ...
}

上手くパースできない場合、勝手にデフォルトエラーページが返る。
→同じくいついかなるときもJsonでレスポンス返したいのでボツ

なぜこうしたか、後々忘れそうなのでメモ。

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0