Reads: recommanded handling of domain logic returning Option?




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")
            (json \ "unite" \ "contentCode").validate[String]
          .flatMap(nameAndContentCode =>
            Foo.of(nameAndContentCode._1, nameAndContentCode._2)
              .getOrElse(JsError(Seq(JsPath() -> Seq(ValidationError("", 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!