move json extract logic to ControllerBase

This commit is contained in:
nazoking
2015-01-20 13:15:33 +09:00
parent 47cb4d1c49
commit 83bcbef6ce
2 changed files with 12 additions and 3 deletions

View File

@@ -14,7 +14,7 @@ import service.{SystemSettingsService, AccountService, AccessTokenService}
import javax.servlet.http.{HttpServletResponse, HttpServletRequest}
import javax.servlet.{FilterChain, ServletResponse, ServletRequest}
import org.scalatra.i18n._
import scala.util.Try
/**
* Provides generic features for controller implementations.
*/
@@ -151,6 +151,15 @@ abstract class ControllerBase extends ScalatraFilter
response.addHeader("X-Content-Type-Options", "nosniff")
rawData
}
// jenkins send message as 'application/x-www-form-urlencoded' but scalatra already parsed as multi-part-request.
def extractFromJsonBody[A](implicit request:HttpServletRequest, mf:Manifest[A]): Option[A] = {
(request.contentType.map(_.split(";").head.toLowerCase) match{
case Some("application/x-www-form-urlencoded") => multiParams.keys.headOption.map(parse(_))
case Some("application/json") => Some(parsedBody)
case _ => Some(parse(request.body))
}).filterNot(_ == JNothing).flatMap(j => Try(j.extract[A]).toOption)
}
}
/**

View File

@@ -181,10 +181,10 @@ trait IssuesControllerBase extends ControllerBase {
* https://developer.github.com/v3/issues/comments/#create-a-comment
*/
post("/api/v3/repos/:owner/:repository/issues/:id/comments")(readableUsersOnly { repository =>
val data = multiParams.keys.headOption.flatMap(b => Try(parse(b).extract[CreateAComment]).toOption)
(for{
issueId <- params("id").toIntOpt
(issue, id) <- handleComment(issueId, data.map(_.body), repository)()
body <- extractFromJsonBody[CreateAComment].map(_.body) if ! body.isEmpty
(issue, id) <- handleComment(issueId, Some(body), repository)()
issueComment <- getComment(repository.owner, repository.name, id.toString())
} yield {
apiJson(WebHookComment(issueComment, WebHookApiUser(context.loginAccount.get)))