Skip to content

Instantly share code, notes, and snippets.

@swsnr
Created August 27, 2019 19:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save swsnr/ec70af3bf8c93055555e3067428fb901 to your computer and use it in GitHub Desktop.
Save swsnr/ec70af3bf8c93055555e3067428fb901 to your computer and use it in GitHub Desktop.
Decode flat ADT with circe
{
"error": "Some error message",
"status": 409
}
{
"type": "record",
"id": 42,
"version": 1
}
import io.circe._
import io.circe.generic.semiauto._
sealed trait Response
final case class Success(`type`: String, id: Int, version: Int)
extends Response
object Success {
implicit val successDecoder: Decoder[Success] = deriveDecoder[Success]
}
final case class Error(error: String, status: Int)
extends Response
object Error {
implicit val errorDecoder: Decoder[Error] = deriveDecoder[Error]
}
object Response {
implicit def responseDecoder(
implicit decodeError: Decoder[Error],
decodeSuccess: Decoder[Success]
): Decoder[Response] = new Decoder[Response] {
override def apply(cursor: HCursor): Result[Response] =
if (cursor.downField("error").succeeded) {
decodeError(cursor)
} else {
decodeSuccess(cursor)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment