Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate parameters in a functional way?

I'm writing Scala/Play 2.0 application, and I want my code to return different page depending on request. Here is my code:

// Validate client and return temporary credentials
def requestToken = Action { request =>
  // Authorization header may present or not
  val authHeader = parseHeaders(request headers AUTHORIZATION)
  // Authorization header may contain such keys or not
  val clientKey = authHeader("oauth_consumer_key")
  val signature = authHeader("oauth_signature")

  if (authenticateClient(clientKey, signature)) {
    ...
    Ok(...)
  } else {
    Unauthorized(...)
  }

}

The problem arise when request is malformed and some headers are missing, then NoSuchElementException is thrown.

In imperative language, I would validate every step like this:

if (!request.headers.contains(AUTHORIZATION))
  return Unathorized

val authHeader = parseHeaders(request headers AUTHORIZATION)

if (!authHeader.contains("oauth_consumer_key") || !authHeader.contains("oauth_signature"))
  return Unathorized

val clientKey = authHeader("oauth_consumer_key")
val signature = authHeader("oauth_signature")

...

but what should I do to solve such problem in a functional way?

like image 710
lambdas Avatar asked Jun 15 '12 05:06

lambdas


1 Answers

You can use authHeader.get(key) which returns an Option[B]. Your code then would look something like this:

val result = for {
  auth <- request.headers.get(AUTHORIZATION)
  authHeader = parseHeaders(auth)
  clientKey <- authHeader.get("oauth_consumer_key")
  signature <- authHeader.get("oauth_signature")
} yield { ... }

result.getOrElse(Unauthorized)

Explanation:

The whole expression will only be executed, if there is no None value. So if all headers are present you will get a result of Some[A] and if one or more are absent, you will get None. result.getOrElse(Unauthorized) will return the contained value for Some[A] and Unauthorized for None.

like image 186
drexin Avatar answered Nov 07 '22 16:11

drexin