下面是一个很常见的 play framework 2 控制器:
def save(ideaId : Long) = CORSAction { request =>
Idea.findById(ideaId).map { idea =>
request.body.asJson.map { json =>
json.asOpt[Comment].map { comment =>
comment.copy(idea = idea).save.fold(
errors => JsonBadRequest(errors),
comment => Ok(toJson(comment).toString)
)
}.getOrElse (JsonBadRequest("Invalid Comment entity"))
}.getOrElse (JsonBadRequest("Expecting JSON data"))
}.getOrElse (JsonBadRequest("Could not find idea with id '%s'".format(ideaId)))
}
我发现所有这些嵌套的 .map 有点烦人,而且我还发现每个错误处理都在底部有点乏味
您将如何改进它以使其更具可读性,同时保持功能性惯用的 scala 代码?
我在想也许是这样的(它是伪代码,仍然无法编译)
def save(ideaId : Long) = CORSAction { request =>
val idea = Idea.findById(ideaId).getOrElse(
return JsonBadRequest("Could not find idea with id '%s'".format(ideaId)))
val json = request.body.asJson.getOrElse(
return JsonBadRequest("Expecting JSON data"))
val comment = json.asOpt[Comment].getOrElse(
return JsonBadRequest("Invalid Comment entity"))
comment.copy(idea = idea).save.fold(
errors => JsonBadRequest(errors),
comment => Ok(toJson(comment).toString)
)
}
ps:我知道最好避免return语句...