Home > OS >  Migrating from Akka Http to Http4s - custom directives
Migrating from Akka Http to Http4s - custom directives

Time:06-21

I'm starting to learn Http4s, at work we may need to migrate Rest APIs implemented with Akka Http to Http4s.

As an example I can define a custom directive like this:

trait CustomDirectives {

  def extractUUID: Directive1[UUID] = {
    path(Segment).flatMap { maybeuuid =>
      Try(UUID.fromString(maybeuuid)) match {
        case Success(result) => provide(result)
        case Failure(_) =>
          complete(StatusCodes.BadRequest, s"Invalid uuid: $maybeuuid")
      }
    }
  }

}

So everytime I want to extract an UUID and validate it I can use this directive. We have other custom directives to make some processing on headers, and many more.

Is there anything similar to akka custom directives but in Http4s?

CodePudding user response:

This is described in Handling Path Parameters section of the documentation

// standard Scala extractor, matching String against UUID
object UUIDVar {
  def unapply(maybeuuid: String): Option[UUID] =
    Try(UUID.fromString(maybeuuid)).toOption
}

val usersService = HttpRoutes.of[IO] {
  // just use extractor in pattern matching
  case GET -> Root / "users" / UUIDVar(uuid) =>
    Ok(useUUIDForSth(uuid))
}

However, personally, I find it easier to describe endpoints with libraries like Tapir or Endpoint4s since their DSL seem more intuitive to me and I am not coupling my code with a particular implementation.

  • Related