类型Option [java.sql.Timestamp]不能用作默认值

时间:2019-03-14 06:07:34

标签: scala sangria

试图从案例类中获取派生的输入对象。

val UserInputType = deriveInputObjectType[UserRow]()
case class UserRow(id: Int, name: String, lastModifiedTime: Option[java.sql.Timestamp] = None) 

但出现以下错误

Type Option[java.sql.Timestamp] cannot be used as a default value. Please consider defining an implicit instance of `ToInput` for it.

我还定义了时间戳的类型:

  case object DateTimeCoerceViolation extends Violation {
    override def errorMessage: String = "Error during parsing DateTime"
  }

  def parseTime(s: String) = Try(Timestamp.valueOf(s)) match {
    case Success(date) ⇒ Right(date)
    case Failure(_) ⇒ Left(DateTimeCoerceViolation)
  }

  implicit val TimestampType = ScalarType[Timestamp](
    "Timestamp",
    coerceOutput = (ts, _) => ts.getTime,
    coerceInput = {
      case StringValue(ts, _, _, _,_) => parseTime(ts)
      case _ => Left(DateTimeCoerceViolation)
    },
    coerceUserInput = {
      case s: String => parseTime(s)
      case _ => Left(DateTimeCoerceViolation)
    }
  )

如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

如错误所述-请考虑为其定义一个ToInput的隐式实例,您必须为ToInput隐式提供Timestamp。因为没有它,桑格利亚汽酒无法将原始数据序列化为Timestamp

  implicit val toInput = new ToInput[Option[java.sql.Timestamp], Json] {
    override def toInput(value: Option[Timestamp]): (Json, InputUnmarshaller[Json]) = value match {
      case Some(time) => (Json.fromString(time.toString), sangria.marshalling.circe.CirceInputUnmarshaller)
      case None => (Json.Null, sangria.marshalling.circe.CirceInputUnmarshaller)
    }
  }

另一方面,如果使用play-json库,则不必显式定义和使用toInput

例如,在play json中,您可以为TimeStamp定义隐式格式。

implicit val timeStampFormat: Format = ???

桑格利亚·詹森·马歇尔(Sangria Json-Marshaller)将隐式使用上述格式将Json序列化为Timestamp