Type Option[java.sql.Timestamp] cannot be used as a default value

1.2k views Asked by At

Trying to get a derived input object from a case class.

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

but getting this following error

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

I have also defined the type for the timestamp:

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

How can solve this ?

1

There are 1 answers

1
Ra Ka On

As the error says - Please consider defining an implicit instance of ToInput for it, you have to provide ToInput for Timestamp implicitly. Because, without it, sangria will not be able to serialize raw data to 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)
    }
  }

On the other hand, if are using play-json library, you don't have to explicitly define and use toInput.

For example, in play json, you can define implicit format for TimeStamp.

implicit val timeStampFormat: Format = ???

Above format will be implicitly used by sangria Json-Marshaller for serializing Json to Timestamp.