尝试从案例类中获取派生的输入对象。
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)
}
)
怎么解决这个?
正如错误所说 - 请考虑为它定义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 = ???
以上格式将由桑格利亚Json-Marshaller隐含地用于将Json
序列化为Timestamp
。