Skip to content

Commit

Permalink
fix: failing FailureSpec
Browse files Browse the repository at this point in the history
  • Loading branch information
jachro committed Sep 11, 2023
1 parent f0b5c0d commit 8a13da6
Showing 1 changed file with 19 additions and 13 deletions.
32 changes: 19 additions & 13 deletions graph-commons/src/main/scala/io/renku/data/MessageCodecs.scala
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ package io.renku.data
import Message._
import cats.effect.Concurrent
import cats.syntax.all._
import io.circe.DecodingFailure.Reason.CustomReason
import io.circe.syntax._
import io.circe.{Decoder, DecodingFailure, Encoder, Json}
import io.renku.graph.model.Schemas.{renku, schema}
Expand All @@ -38,24 +39,29 @@ trait MessageCodecs {
case Severity.Info.value => Severity.Info.widen.asRight
case Severity.Error.value => Severity.Error.widen.asRight
case other =>
DecodingFailure(DecodingFailure.Reason.CustomReason(s"unknown Message.Severity '$other'"), cur).asLeft
DecodingFailure(CustomReason(s"unknown Message.Severity '$other'"), cur).asLeft
}

implicit lazy val severityEncoder: Encoder[Severity] = _.value.asJson

implicit lazy val messageJsonDecoder: Decoder[Message] = Decoder.instance[Message] { cur =>
for {
severity <- cur.downField("severity").as[Message.Severity]
messageJson <- cur.downField("message").as[Json]
message <- if (messageJson.isString) messageJson.as[String].map(Message.unsafeApply(_, severity))
else if (messageJson.isObject && severity == Message.Severity.Error)
Message.Error.fromJsonUnsafe(messageJson).asRight
else
DecodingFailure(
DecodingFailure.Reason.CustomReason(s"Malformed '$severity' Message with '$messageJson'"),
cur
).asLeft
} yield message
def toMessage(severity: Severity): Json => Decoder.Result[Message] = { messageJson =>
if (messageJson.isString)
messageJson.as[String].map(Message.unsafeApply(_, severity))
else if (severity == Message.Severity.Error)
Message.Error.fromJsonUnsafe(messageJson).asRight
else
DecodingFailure(CustomReason(s"Malformed '$severity' Message with '$messageJson'"), cur).asLeft
}

cur.downField("severity").as[Message.Severity] >>= { severity =>
cur.keys.toList.flatMap(_.filterNot(_ == "severity").toList) match {
case "message" :: Nil =>
cur.downField("message").as[Json] >>= toMessage(severity)
case _ =>
cur.downField("severity").delete.as[Json] >>= toMessage(severity)
}
}
}

implicit def messageJsonEncoder[T <: Message]: Encoder[T] = Encoder.instance[T] {
Expand Down

0 comments on commit 8a13da6

Please sign in to comment.