【问题标题】:Create custom DynamoDB format for my sealed Trait为我的密封特征创建自定义 DynamoDB 格式
【发布时间】:2020-10-22 10:21:28
【问题描述】:

我对 DynamoDB 完全陌生,并试图在其中插入一些数据。 我有一个这样的案例类

case class JobInfo(
                    jobId: String,
                    status: JobStatus,
                    name: String,
                    scheduledTime: DateTime,
                    startTime: Option[DateTime] = None,
                    endTime: Option[DateTime] = None,
                    organisationId: Option[String] = None
                  )

我已经像这样为这个类定义了隐式

implicit val formatFarm: DynamoFormat[JobInfo] = deriveDynamoFormat[JobInfo]

本案例类中的一个字段是jJobStatus,定义为

sealed trait JobStatus {
  def status: String
}

object JobStatus {
  case object Waiting extends JobStatus { val status = "waiting" }
  case object Running extends JobStatus { val status = "running" }
  case object Success extends JobStatus { val status = "success" }
  case object Failure extends JobStatus { val status = "failure" }
}

为了将数据插入 Mongo,我已经编写了隐式编解码器,但我不确定如何为工作状态的发电机编写它 我试过implicit val dynamocodec = deriveDynamoFormat[JobStatus] 但是当我将数据插入到表的 DynamoDB 中时

val table = Table[JobInfo]("testJob")

如下所示:

table.put(JobInfo("2", Waiting , "job2", DateTime.parse("2016-11-07T15:29:20.348+0000"),None, None, Some("orgid2")))

,Status 列的添加类似于

{ "Waiting" : { "S" : "Waiting" } } in dynamo table

它应该是小写的“等待”。 我认为 JobStatus 的 dynamoformat 必须是别的东西,如果有人可以帮助我。

【问题讨论】:

    标签: scala amazon-dynamodb


    【解决方案1】:

    我自己翻阅了图书馆后得到了答案。在网上找不到这个答案,所以想自己发帖

    sealed trait JobStatus1 {
      def status: String
    }
    
            object JobStatus1 {
          case object Waiting1 extends JobStatus1 { val status = "waiting" }
          case object Running1 extends JobStatus1 { val status = "running" }
          case object Success1 extends JobStatus1 { val status = "success" }
          case object Failure1 extends JobStatus1 { val status = "failure" }
        
          def getJobStatusFromString(name: String): Either[DynamoReadError, JobStatus1] = name match {
            case Waiting1.status => Right(Waiting1)
            case Running1.status => Right(Running1)
            case Success1.status => Right(Success1)
            case Failure1.status => Right(Failure1)
            case _ => Left(TypeCoercionError(new Exception(" invalid value")))
        
          }
    
        implicit val jobStatusFormat = DynamoFormat.xmap[JobStatus1, String]( JobStatus1.getJobStatusFromString(_) ,_.status)
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-04-04
      • 1970-01-01
      • 2015-05-26
      • 1970-01-01
      • 2015-09-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多