Skip to content

Commit

Permalink
Add test for constructing Writes with case class
Browse files Browse the repository at this point in the history
Updated syntax in README to support Scala 3
  • Loading branch information
Donovan Levinson committed May 13, 2024
1 parent 51bd5d6 commit 4aee6a7
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 3 deletions.
15 changes: 12 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -246,19 +246,28 @@ import play.api.libs.functional.syntax._
implicit val locationWrites: Writes[Location] = (
(JsPath \ "lat").write[Double] and
(JsPath \ "long").write[Double]
)(unlift(Location.unapply))
)(location => {
val Location(lat, long) = location
(lat, long)
})

implicit val residentWrites: Writes[Resident] = (
(JsPath \ "name").write[String] and
(JsPath \ "age").write[Int] and
(JsPath \ "role").writeNullable[String]
)(unlift(Resident.unapply))
)(resident => {
val Resident(name, age, role) = resident
(name, age, role)
})

implicit val placeWrites: Writes[Place] = (
(JsPath \ "name").write[String] and
(JsPath \ "location").write[Location] and
(JsPath \ "residents").write[Seq[Resident]]
)(unlift(Place.unapply))
)(place => {
val Place(name, location, residents) = place
(name, location, residents)
})


val place = Place(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,31 @@ final class WritesSharedSpec extends AnyWordSpec with Matchers {
success[JsValue, Writes](JsString("foo"))
}

"Constructing Writes" should {
"support case class" in {
import play.api.libs.functional.syntax._

implicit val locationReads: Reads[Location] = (
(JsPath \ "lat").read[Double] and
(JsPath \ "long").read[Double]
)(Location.apply _)

implicit val locationWrites: Writes[Location] = (
(JsPath \ "lat").write[Double] and
(JsPath \ "long").write[Double]
)(location => {
val Location(lat, long) = location
(lat, long)
})

val location = Location(1.1, 2.2)

val serialized = Json.stringify(Json.toJson(location))
serialized.mustEqual("""{"lat":1.1,"long":2.2}""")
Json.fromJson[Location](Json.parse(serialized)).mustEqual(JsSuccess(location))
}
}

// ---

case class Location(lat: Double, long: Double)
Expand Down

0 comments on commit 4aee6a7

Please sign in to comment.