Skip to content

updateNullable #414

Description

@jroper

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"))
      }
  }

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions