1

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

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

如何解决这个问题?

4

1 回答 1

1

正如错误所说 -请考虑ToInput为它定义一个隐式实例,你必须隐式地ToInput提供Timestamp。因为,没有它,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.

于 2019-03-29T12:02:58.577 回答