Akka-Http
structible-akka-http is available for Scala 2.12 and 2.13.
It provides derivations for:
- PathMatcher
- Unmarshaller
Make sure to familiarize yourself with creating structible instances before looking at the examples below.
Dependency
- sbt
libraryDependencies += "com.github.cerst" % "structible-akka-http" % "0.6.4"
- Maven
<dependency> <groupId>com.github.cerst</groupId> <artifactId>structible-akka-http</artifactId> <version>0.6.4</version> </dependency>
- Gradle
dependencies { compile group: 'com.github.cerst', name: 'structible-akka-http', version: '0.6.4' }
PathMatcher Example
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.{PathMatcher1, Route}
import com.github.cerst.structible.akkahttp.ops._
import com.github.cerst.structible.core.DefaultConstraints._
import com.github.cerst.structible.core._
object PathMatcherExample {
final class ItemId private (val value: Long) extends AnyVal
object ItemId {
private val structible: Structible[Long, ItemId] = Structible.structible(new ItemId(_), _.value, c >= 0)
// not declared as implicit because you usually call patch matchers explicitly within the Akka routing Dsl
val pathMatcher: PathMatcher1[ItemId] = structible.toPathMatcher
def apply(value: Long): ItemId = structible.construct(value)
}
val route: Route = {
path("items" / ItemId.pathMatcher) { itemId =>
complete(itemId.toString)
}
}
}
Unmarshaller Example
This derivation was originally added to address a quirk in an Http Api which returned the id of a generated resource as plain text. Hence, the response entity needed to be unmarshalled directly as in Unmarshal(response.entity).to[A].
As long as you receive a properly formatted message, use a derivation for the employed messaging protocol and library (e.g. your favorite JSON library).
import akka.http.scaladsl.unmarshalling.{Unmarshal, Unmarshaller}
import akka.stream.Materializer
import com.github.cerst.structible.akkahttp.ops._
import com.github.cerst.structible.core.DefaultConstraints._
import com.github.cerst.structible.core._
import scala.concurrent.{ExecutionContext, Future}
object UnmarshallerExample {
final class ItemId private (val value: Long) extends AnyVal
object ItemId {
private val structible: Structible[Long, ItemId] = Structible.structible(new ItemId(_), _.value, c >= 0)
implicit val unmarshallerForItemId: Unmarshaller[String, ItemId] = structible.toUnmarshaller
def apply(value: Long): ItemId = structible.construct(value)
}
// this works seamlessly for e.g. HttpResponse.entity instead of String
def toItemId(input: String)(implicit ec: ExecutionContext, mat: Materializer): Future[ItemId] = {
Unmarshal(input).to[ItemId]
}
}
The source code for this page can be found here.