aboutsummaryrefslogtreecommitdiff
path: root/src/main/scala/xyz/driver/pdsuidomain/formats/json/user/ApiUser.scala
blob: 8dbedfee96a0edade38f4686d57d66275879ed60 (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
package xyz.driver.pdsuidomain.formats.json.user

import java.time.{ZoneId, ZonedDateTime}

import xyz.driver.pdsuicommon.domain.User
import play.api.data.validation.ValidationError
import play.api.libs.functional.syntax._
import play.api.libs.json._

final case class ApiUser(id: String,
                         email: String,
                         name: String,
                         roleId: String,
                         latestActivity: Option[ZonedDateTime])

object ApiUser {

  implicit val format: Format[ApiUser] = (
    (JsPath \ "id").format[String] and
      (JsPath \ "email").format[String](Reads.email) and
      (JsPath \ "name").format[String] and
      (JsPath \ "roleId").format[String](
        Format(Reads
                 .of[String]
                 .filter(ValidationError("unknown role"))({
                   case x if UserRole.roleFromString.isDefinedAt(x) => true
                   case _                                           => false
                 }),
               Writes.of[String])) and
      (JsPath \ "latestActivity").formatNullable[ZonedDateTime]
  )(ApiUser.apply, unlift(ApiUser.unapply))

  def fromDomain(user: User) = ApiUser(
    user.id.id,
    user.email.value,
    user.name,
    UserRole.roleToString(user.role),
    user.latestActivity.map(ZonedDateTime.of(_, ZoneId.of("Z")))
  )
}