aboutsummaryrefslogtreecommitdiff
path: root/src/main/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/intervention.scala
blob: a8ce950d0e00a72139a8abdbac116515021a5335 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package xyz.driver.pdsuidomain.formats.json.sprayformats

import spray.json._
import xyz.driver.pdsuicommon.domain.LongId
import xyz.driver.pdsuidomain.entities._

object intervention {
  import DefaultJsonProtocol._
  import common._

  implicit val interventionWriter: JsonWriter[InterventionWithArms] = new JsonWriter[InterventionWithArms] {
    override def write(obj: InterventionWithArms) =
      JsObject(
        "id"                  -> obj.intervention.id.toJson,
        "name"                -> obj.intervention.name.toJson,
        "typeId"              -> obj.intervention.typeId.toJson,
        "description"         -> obj.intervention.description.toJson,
        "isActive"            -> obj.intervention.isActive.toJson,
        "arms"                -> obj.arms.map(_.armId).toJson,
        "trialId"             -> obj.intervention.trialId.toJson,
        "originalName"        -> obj.intervention.originalName.toJson,
        "originalDescription" -> obj.intervention.originalDescription.toJson,
        "originalType"        -> obj.intervention.originalType.toJson
      )
  }

  def applyUpdateToInterventionWithArms(json: JsValue, orig: InterventionWithArms): InterventionWithArms = json match {
    case JsObject(fields) =>
      val typeId = fields
        .get("typeId")
        .map(_.convertTo[LongId[InterventionType]])

      val description = fields
        .get("description")
        .map(_.convertTo[String])

      val isActive = fields
        .get("isActive")
        .map(_.convertTo[Boolean])

      val origIntervention = orig.intervention
      val arms = fields
        .get("arms")
        .map(_.convertTo[List[LongId[Arm]]].map(x => InterventionArm(x, orig.intervention.id)))

      orig.copy(
        intervention = origIntervention.copy(
          typeId = typeId.orElse(origIntervention.typeId),
          description = description.getOrElse(origIntervention.description),
          isActive = isActive.getOrElse(origIntervention.isActive)
        ),
        arms = arms.getOrElse(orig.arms)
      )

    case _ => deserializationError(s"Expected Json Object as partial Intervention, but got $json")
  }

  implicit val interventionTypeFormat: RootJsonFormat[InterventionType] = jsonFormat2(InterventionType.apply)

}