optionalAttribute

Signature

def optionalAttribute[T](key: AttributeKey[T]): Directive1[Option[T]] 

Description

Optionally extracts the value of the request attribute with the given key.

The optionalAttribute directive is similar to the attribute directive but always extracts an Option value instead of rejecting the request if no matching attribute could be found.

Example

Scala
Java
sourceval userId = AttributeKey[String]("user-id")

val route =
  optionalAttribute(userId) {
    case Some(userId) => complete(s"The user is $userId")
    case None         => complete(s"No user was provided")
  } ~ // can also be written as:
  optionalAttribute(userId) { userId =>
    complete {
      userId match {
        case Some(u) => s"The user is $u"
        case _       => "No user was provided"
      }
    }
  }

// tests:
Get("/") ~> addAttribute(userId, "Joe42") ~> route ~> check {
  responseAs[String] shouldEqual "The user is Joe42"
}
Get("/") ~> Route.seal(route) ~> check {
  responseAs[String] shouldEqual "No user was provided"
}
sourceAttributeKey<String> userId = AttributeKey.create("user-id", String.class);

final Route route =
    optionalAttribute(
        userId,
        id -> {
          if (id.isPresent()) {
            return complete("The user is " + id.get());
          } else {
            return complete("No user was provided");
          }
        });

// tests:
testRoute(route)
    .run(HttpRequest.GET("/").addAttribute(userId, "Joe42"))
    .assertEntity("The user is Joe42");

testRoute(route).run(HttpRequest.GET("/")).assertEntity("No user was provided");