Skip to content

Commit

Permalink
Add Decoder method for indicating what should be returned on null path
Browse files Browse the repository at this point in the history
  • Loading branch information
alejandrohdezma committed Apr 7, 2020
1 parent 2c0e1bc commit c2e1c65
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 5 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,13 @@ trait Decoder[A] {
/** Decode the given [[Json.Value]] */
def decode(json: Json.Value): Try[A]

/**
* What should this decoder return if a `Null` is found on the path to getting the value.
*
* This doesn't affect when the value itself is `Null`.
*/
def onNullPath: Try[A] = NotFound.raise

}

object Decoder {
Expand Down Expand Up @@ -72,9 +79,15 @@ object Decoder {
case value => NotADateTime(value).raise
}

implicit def OptionDecoder[A: Decoder]: Decoder[Option[A]] = {
case Json.Null => Try(None)
case value => Decoder[A].decode(value).map(Some(_))
implicit def OptionDecoder[A: Decoder]: Decoder[Option[A]] = new Decoder[Option[A]] {

override def decode(json: Json.Value): Try[Option[A]] = json match {
case Json.Null => Try(None)
case value => Decoder[A].decode(value).map(Some(_))
}

override def onNullPath: Try[Option[A]] = Try(None)

}

implicit def ListDecoder[A: Decoder]: Decoder[List[A]] = {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ package com.alejandrohdezma.sbt.github.syntax
import scala.annotation.tailrec
import scala.util.Try

import com.alejandrohdezma.sbt.github.error.NotFound
import com.alejandrohdezma.sbt.github.json.error.{InvalidPath, NotAJSONObject}
import com.alejandrohdezma.sbt.github.json.{Decoder, Json}
import com.alejandrohdezma.sbt.github.syntax.scalatry._
Expand Down Expand Up @@ -49,7 +48,7 @@ object json {
): Try[A] = (value, remain) match {
case (j: Json.Value, Nil) => j.as[A].mapFail(done.foldRight(_)(InvalidPath))
case (j: Json.Object, h :: t) => recursiveGet(j.get(h), t, done :+ h)
case (Json.Null, _) => done.foldRight(NotFound: Throwable)(InvalidPath).raise
case (Json.Null, _) => Decoder[A].onNullPath.mapFail(done.foldRight(_)(InvalidPath))
case (v, _) => done.foldRight(NotAJSONObject(v): Throwable)(InvalidPath).raise
}

Expand Down

0 comments on commit c2e1c65

Please sign in to comment.