Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
package zio.schema.json

import zio.schema.DynamicValue

sealed trait JsonPatch {

def apply(target: DynamicValue): Either[String, DynamicValue] = this match {
case JsonPatch.Add(path, value) =>
val key = path.stripPrefix("/")
if (key == "") {
Left("path cannot be empty")
} else {
target match {
case DynamicValue.Record(id, fields) =>
Right(DynamicValue.Record(id, fields.updated(key, value)))
case _ =>
Left("expected record")
}
}

case JsonPatch.Remove(path) =>
val key = path.stripPrefix("/")
if (key == "") {
Left("path cannot be empty")
} else {
target match {
case DynamicValue.Record(id, fields) =>
if (fields.contains(key)) {
Right(DynamicValue.Record(id, fields - key))
} else {
Left(s"path $key not found")
}
case _ =>
Left("expected record")
}
}
}
}

object JsonPatch {
final case class Add(path: String, value: DynamicValue) extends JsonPatch
final case class Remove(path: String) extends JsonPatch
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package zio.schema.json

import scala.collection.immutable.ListMap

import zio.schema.{ DynamicValue, TypeId }
import zio.test._

object JsonPatchSpec extends ZIOSpecDefault {
override def spec: Spec[Any, Any] = suite("JsonPatch Spec")(
test("Add: should add field to record") {
val user = TypeId.parse("User")
val data = ListMap("name" -> DynamicValue("Akshaya"))
val record = DynamicValue.Record(user, data)

val patch = JsonPatch.Add("/age", DynamicValue(25))
val result = patch.apply(record)

val expectedData = ListMap("name" -> DynamicValue("Akshaya"), "age" -> DynamicValue(25))
val expected = DynamicValue.Record(user, expectedData)

assertTrue(result == Right(expected))
},
test("Remove: should remove field from record") {
val user = TypeId.parse("User")
val data = ListMap("name" -> DynamicValue("Akshaya"))
val record = DynamicValue.Record(user, data)

val patch = JsonPatch.Remove("/name")
val result = patch.apply(record)

val expected = DynamicValue.Record(user, ListMap.empty[String, DynamicValue])

assertTrue(result == Right(expected))
},
test("Failure: target is not a record") {
val patch = JsonPatch.Remove("/any")
val result = patch.apply(DynamicValue("random-string"))

assertTrue(result == Left("expected record"))
}
)
}