From e71129f5f5cc39fe5ff307262226f3d241e20456 Mon Sep 17 00:00:00 2001 From: Dilyan Damyanov Date: Mon, 4 Nov 2019 12:50:34 +0000 Subject: [PATCH] Fix empty contexts and unstruct_event decoding (closes #92) --- .../SnowplowEvent.scala | 28 +++++++++---------- .../EventSpec.scala | 3 -- 2 files changed, 14 insertions(+), 17 deletions(-) diff --git a/src/main/scala/com.snowplowanalytics.snowplow.analytics.scalasdk/SnowplowEvent.scala b/src/main/scala/com.snowplowanalytics.snowplow.analytics.scalasdk/SnowplowEvent.scala index 676877a..599c5a1 100644 --- a/src/main/scala/com.snowplowanalytics.snowplow.analytics.scalasdk/SnowplowEvent.scala +++ b/src/main/scala/com.snowplowanalytics.snowplow.analytics.scalasdk/SnowplowEvent.scala @@ -41,6 +41,19 @@ object SnowplowEvent { } } + implicit final val unstructCirceEncoder: Encoder[UnstructEvent] = + Encoder.instance { unstructEvent: UnstructEvent => + if (unstructEvent.data.isEmpty) Json.Null + else JsonObject( + ("schema", Common.UnstructEventUri.toSchemaUri.asJson), + ("data", unstructEvent.data.asJson) + ).asJson + } + + implicit val unstructEventDecoder: Decoder[UnstructEvent] = deriveDecoder[UnstructEvent].recover { + case DecodingFailure(_, DownField("data") :: _) => UnstructEvent(None) + } + /** * A JSON representation of an atomic event's contexts or derived_contexts fields. * @@ -67,20 +80,7 @@ object SnowplowEvent { } implicit val contextsDecoder: Decoder[Contexts] = deriveDecoder[Contexts].recover { - case DecodingFailure(_, l) if l.contains(DownField("data")) => Contexts(List()) - } - - implicit final val unstructCirceEncoder: Encoder[UnstructEvent] = - Encoder.instance { unstructEvent: UnstructEvent => - if (unstructEvent.data.isEmpty) Json.Null - else JsonObject( - ("schema", Common.UnstructEventUri.toSchemaUri.asJson), - ("data", unstructEvent.data.asJson) - ).asJson - } - - implicit val unstructEventDecoder: Decoder[UnstructEvent] = deriveDecoder[UnstructEvent].recover { - case DecodingFailure(_, l) if l.contains(DownField("data")) => UnstructEvent(None) + case DecodingFailure(_, DownField("data") :: _) => Contexts(List()) } /** diff --git a/src/test/scala/com.snowplowanalytics.snowplow.analytics.scalasdk/EventSpec.scala b/src/test/scala/com.snowplowanalytics.snowplow.analytics.scalasdk/EventSpec.scala index bde777d..d78ee64 100644 --- a/src/test/scala/com.snowplowanalytics.snowplow.analytics.scalasdk/EventSpec.scala +++ b/src/test/scala/com.snowplowanalytics.snowplow.analytics.scalasdk/EventSpec.scala @@ -3047,9 +3047,6 @@ class EventSpec extends Specification { val tempJsonStr = tempInstance.asJson.noSpaces val tempJson = parse(tempJsonStr).getOrElse(throw new RuntimeException("Error while converting to json")) tempJson.as[Temp].map(_.event) must beRight(event) -// val eventJsonStr = event.toJson(false).noSpaces -// val eventJson = parse(eventJsonStr).getOrElse(throw new RuntimeException("Error while converting to json")) -// eventJson.as[Event] must beRight(event) } }