Reads: recommanded handling of domain logic returning Option?

scala

#1

Hi

I parse some Json content and then give it to the domain which returns an option.

Ideally it could be something along the lines of:

      (JsPath \ "name").read[String] and
        (JsPath \ "unite" \ "contentCode").read[String]
      ) (Foo.of(_, _).get

But as you see I do a get on the returned Option[Foo], which isn’t right for sure.

So far my best try to solve this is:

new Reads[Foo] {
      override def reads(json: JsValue): JsResult[Foo] = {
        (json \ "name")
          .validate[String]
          .and(
            (json \ "unite" \ "contentCode").validate[String]
          )
          .tupled
          .flatMap(nameAndContentCode =>
            Foo.of(nameAndContentCode._1, nameAndContentCode._2)
              .map(JsSuccess(_))
              .getOrElse(JsError(Seq(JsPath() -> Seq(ValidationError("error.invalid.foo", nameAndContentCode))))))
      }
    }

but the increased verbosity makes me worry I’ve missed some better way… Do you know of any?

I also worry about the JsPath in the JsError not being properly filled in…

thanks in advance!