Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

updateNullable #414

Open
jroper opened this issue Feb 10, 2020 · 0 comments
Open

updateNullable #414

jroper opened this issue Feb 10, 2020 · 0 comments
Labels

Comments

@jroper
Copy link
Member

jroper commented Feb 10, 2020

It would be great if JsPath supported the ability to update a path if it exists. Currently, if you try to define an update on a path that doesn't exist, you'll get an error. Here's a helper that does this:

private implicit class PathUpdateNullable(path: JsPath) {
    def updateNullable[A <: JsValue](reads: Reads[A]) =
      Reads[JsObject] {
        case o: JsObject =>
          path.asSingleJson(o) match {
            case JsDefined(jsv) =>
              val updated = reads.reads(jsv).repath(path)
              updated.map { updatedJsv =>
                o.deepMerge(JsPath.createObj(path -> updatedJsv))
              }
            case _ => JsSuccess(o)
          }
        case _ =>
          JsError(JsPath, JsonValidationError("error.expected.jsobject"))
      }
  }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant