diff --git a/core/src/main/scala/sttp/model/sse/ServerSentEvent.scala b/core/src/main/scala/sttp/model/sse/ServerSentEvent.scala index 81dfa809..34020d44 100644 --- a/core/src/main/scala/sttp/model/sse/ServerSentEvent.scala +++ b/core/src/main/scala/sttp/model/sse/ServerSentEvent.scala @@ -3,11 +3,11 @@ package sttp.model.sse import scala.util.Try case class ServerSentEvent( - data: Option[String] = None, - eventType: Option[String] = None, - id: Option[String] = None, - retry: Option[Int] = None -) + data: Option[String] = None, + eventType: Option[String] = None, + id: Option[String] = None, + retry: Option[Int] = None + ) object ServerSentEvent { // https://html.spec.whatwg.org/multipage/server-sent-events.html @@ -24,10 +24,18 @@ object ServerSentEvent { } } + def composeSSE(sse: ServerSentEvent): String = { + val data = sse.data.map(_.split("\n")).map(_.map(line => Some(s"data: $line"))).getOrElse(Array.empty[Option[String]]) + val event = sse.eventType.map(event => s"event: $event") + val id = sse.id.map(id => s"id: $id") + val retry = sse.retry.map(retryCount => s"retry: $retryCount") + (data :+ event :+ id :+ retry).flatten.mkString("\n") + } + private def combineData(event: ServerSentEvent, newData: String): ServerSentEvent = { event match { - case e @ ServerSentEvent(Some(oldData), _, _, _) => e.copy(data = Some(s"$oldData\n$newData")) - case e @ ServerSentEvent(None, _, _, _) => e.copy(data = Some(newData)) + case e@ServerSentEvent(Some(oldData), _, _, _) => e.copy(data = Some(s"$oldData\n$newData")) + case e@ServerSentEvent(None, _, _, _) => e.copy(data = Some(newData)) } } diff --git a/core/src/test/scala/sttp/model/sse/ServerSentEventTest.scala b/core/src/test/scala/sttp/model/sse/ServerSentEventTest.scala index 6028dba2..255fcba4 100644 --- a/core/src/test/scala/sttp/model/sse/ServerSentEventTest.scala +++ b/core/src/test/scala/sttp/model/sse/ServerSentEventTest.scala @@ -28,4 +28,38 @@ class ServerSentEventTest extends AnyFlatSpec with Matchers { ServerSentEvent.parse(lines) shouldBe expected } } + + + "composeSSE" should "successfully serialise Server Sent Event with all fields set" in { + val sse = ServerSentEvent(Some("data"), Some("event"), Some("id1"), Some(10)) + ServerSentEvent.composeSSE(sse) shouldBe + s"""data: data + |event: event + |id: id1 + |retry: 10""".stripMargin + } + + "composeSSE" should "omit fields that are not set" in { + val sse = ServerSentEvent(Some("data"), None, Some("id1"), None) + ServerSentEvent.composeSSE(sse) shouldBe + s"""data: data + |id: id1""".stripMargin + } + + "composeSSE" should "successfully serialise multiline data event" in { + val sse = ServerSentEvent( + Some( + """some data info 1 + |some data info 2 + |some data info 3""".stripMargin), + None, + None, + None + ) + + ServerSentEvent.composeSSE(sse) shouldBe + s"""data: some data info 1 + |data: some data info 2 + |data: some data info 3""".stripMargin + } }