Skip to content

Instantly share code, notes, and snippets.

@asethia
Created May 24, 2018 02:31
Show Gist options
  • Save asethia/dd33296a5efd767fc45d2413b485fc10 to your computer and use it in GitHub Desktop.
Save asethia/dd33296a5efd767fc45d2413b485fc10 to your computer and use it in GitHub Desktop.
This example shows how we can expose REST Akka Http end point using Source Streaming
import akka.NotUsed
import akka.http.scaladsl.common.{EntityStreamingSupport, JsonEntityStreamingSupport}
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport
import akka.http.scaladsl.model.headers.Accept
import akka.http.scaladsl.model.{MediaRange, MediaTypes}
import akka.http.scaladsl.server.{Directives, Route}
import akka.http.scaladsl.testkit.ScalatestRouteTest
import akka.stream.scaladsl.Source
import org.scalatest.{Matchers, WordSpec, WordSpecLike}
import spray.json.DefaultJsonProtocol
/**
* Created by arun sethia on 5/21/18.
*/
class RestSourceStream extends WordSpec with WordSpecLike
with Matchers
with ScalatestRouteTest
with Directives with DefaultJsonProtocol
with SprayJsonSupport {
implicit val jsonStreamingSupport: JsonEntityStreamingSupport = EntityStreamingSupport.json()
val AcceptJson = Accept(MediaRange(MediaTypes.`application/json`))
val AcceptXml = Accept(MediaRange(MediaTypes.`text/xml`))
case class Tweet(uid: Int, txt: String)
case class Measurement(id: String, value: Int)
implicit val tweetFormat = jsonFormat2(Tweet.apply)
implicit val measurementFormat = jsonFormat2(Measurement.apply)
val route: Route =
path("tweets" / Segment) { n =>
// [3] simply complete a request with a source of tweets:
val tweets: Source[Tweet, NotUsed] = Source.repeat[Tweet](Tweet(12, "Hello World!")).take(n.toInt)
complete(tweets)
}
"tweet" should {
"get 10 tweets" in {
Get("/tweets/10").withHeaders(AcceptJson) ~> route ~> check {
assert(responseAs[List[Tweet]].length==10)
}
}
"get 20 tweets" in {
Get("/tweets/20").withHeaders(AcceptJson) ~> route ~> check {
assert(responseAs[List[Tweet]].length==20)
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment