I have a piece of code that I would like to refactor but can't figure how to do it. This is a method from a Play controller where I have to verify many precondition and respond different status for each case :
- resource should exist or 404
- revision should match the
If-Match
value or 412 - payload should be valid or 422
The first attempt looks like below. How do you implement such a suite of verifications?
service.find(key).map { resource =>
request.headers.get("If-Match").map { expected =>
if ( resource.revision == expected ) {
val payload = request.body.validate[Model]
payload match {
case JsSuccess(model, _) =>
Ok()
case JsError(errors) =>
UnprocessableEntity()
}
} else {
PreconditionFailed()
}
}
} getOrElse {
NotFound()
}
My best attempt is now to have one method who create a triplet of Option[Resource], String, JsResult[Model]
and use pattern matching for each case :
condition match {
case (None, _, _) =>
NotFound()
case (Some(resource), expected, _) if ( resource.revision!=expected ) =>
PreconditionFailed()
case (_, _, JsError(errors)) =>
UnprocessableEntity()
case (Some(resource), _, JsSuccess(model, _)) =>
Ok()
}