Playframework Akka WebSocket.accept How to Use Derived Classes and MessageFlowTransformer

Using Playframework 2.5, Akka, and Websockets, I would like to be able to declare a website that accepts different incoming and outgoing classes, these classes will have a base class (one base class for incoming and another for outgoing messages). This is where I am:

object IncomingMessage {
    val subscribeMessage = "subscribe"
    val unsubscribeMessage = "unsubscribe"
}

abstract class IncomingMessage(action: String)

case class SubscribeMessage(repository: String, interval: Int, action: String = IncomingMessage.subscribeMessage) extends IncomingMessage(action)
case class UnsubscribeMessage(repository: String, action: String = IncomingMessage.unsubscribeMessage) extends IncomingMessage(action)

object SubscribeMessage {
    implicit val SubscribeMessageWrites: Reads[SubscribeMessage] = (
        (JsPath \ "repository").read[String] and
        (JsPath \ "interval").read[Int](min(1)) and
        (JsPath \ "action").read[String]
    )(SubscribeMessage.apply _)
}

object UnsubscribeMessage {
    implicit val UnsubscribeMessageWrites: Reads[UnsubscribeMessage] = (
        (JsPath \ "repository").read[String] and
        (JsPath \ "action").read[String]
    )(UnsubscribeMessage.apply _)
}

Outgoing messages are based on one main thing, so I won’t show them.

Reading Play documentation I would do something like this

import play.api.libs.json._
import play.api.mvc.WebSocket.FrameFormatter
implicit val incomingFormat = Json.format[IncomingMessage]
implicit val outcomingFormat = Json.format[OutcomingMessage]

implicit val messageFlowTransformer = MessageFlowTransformer.jsonMessageFlowTransformer[IncomingMessage, OutcomingMessage]

...

def socket = WebSocket.acceptOrResult[IncomingMessage, OutcomingMessage] { ... }

I would like to use formatters and MessageFlowTransformer to send messages without changing them explicitly to json, so I don't want to write:

out ! Json.toJson(outcomingMessage)

But I would like to write

out ! outcomingMessage

But I am returning a compile time error for the imp val val incomingFormat AND the implicit val outcomingFormat

No unapply or unapplySeq function found

? websocket ?

+4

All Articles