Skip to content

Instantly share code, notes, and snippets.

@mathieuancelin
Last active December 22, 2015 00:18
Show Gist options
  • Save mathieuancelin/6387848 to your computer and use it in GitHub Desktop.
Save mathieuancelin/6387848 to your computer and use it in GitHub Desktop.
case class Operation(id: String, amount: Int, access: String)
object Application extends Controller {
val format = Json.format[Operation]
def userFeed(role: String, lower: Int, high: Int) = Action {
val enumerator: Enumerator[Array[Byte]] = WS.url("http://host:port/stream").withTimeout(-1).getStream
val secure: Enumeratee[Operation, Operation] = Enumeratee.collect[Operation] {
case e@Operation(_, _, "private") if role == "MANAGER" => e
case e@Operation(_, _, "public") => e
}
val inBounds = Enumeratee.collect[Operation] {
case e@Operation(_, amount, _) if amount > lower && amount < high => e
}
Ok.feed(
enumerator &>
Enumeratee.map[Array[Byte]](Json.parse) &>
Enumeratee.map[JsValue](format.reads) &>
Enumeratee.collect[JsResult[Operation]] { case JsSuccess(value, _) => value } &>
secure &>
inBounds &>
Enumeratee.map[Operation](format.writes) &>
EventSource()
).as("text/event-stream")
}
}
GET /stream controllers.Streams.stream
object Streams extends Controller {
def stream = Action {
val operations: Enumerator[JsValue] = Enumerator.generateM[JsValue] {
Promise.timeout(
Some( Json.obj(
"id" -> UUID.randomUUID().toString(),
"amount" -> Random.nextInt(1000),
"access" -> if (Random.nextBoolean) "public" else "private"
) ),
500
)
}
Ok.chunked( operations )
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment