【问题标题】:Type Option[java.sql.Timestamp] cannot be used as a default valueType Option[java.sql.Timestamp] 不能用作默认值
【发布时间】:2019-03-29 20:18:10
【问题描述】:

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

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)
    }
  )

如何解决这个问题?

【问题讨论】:

  • 重现问题非常困难。你能分享更多细节吗?
  • Scala 不是引发错误的那个。桑格利亚群岛github.com/sangria-graphql/sangria/issues/224
  • 为了每个人的利益,在桑格利亚汽酒中实现这一目标似乎有些复杂。如果您有 case class A(id: Int, name: String, lastModifiedTime: Option[Timestamp] = None) 这样的案例类,则必须删除 = None 并在案例类之外处理时间的默认输入。

标签: scala sangria


【解决方案1】:

正如错误所说 - 请考虑为其定义 ToInput 的隐式实例,您必须为 Timestamp 隐式提供 ToInput。因为没有它,sangria 将无法将原始数据序列化为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

【讨论】:

  • 这解决了我必须为类型 Option[T] 设置默认值的问题
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-28
  • 2013-12-25
  • 2020-04-22
  • 1970-01-01
  • 2012-01-09
相关资源
最近更新 更多