15

Circe in slick を使用して json でデータを取得しているときに(Timestamp/DateTime)、エンティティに日付フィールドを持たないデータを取得できました。しかしTimestamp、エンティティでフィールドを使用すると、エラーがスローされます。

[error] /var/www/html/scala-api/src/main/scala/oc/api/http/routes/TestApi.scala:40: could not find implicit value for parameter encoder: io.circe.Encoder[Seq[oc.api.models.UserEntity]]
[error]             auth => complete(userDao.getAll().map(_.asJson))

これがコードです。Slick Entities に使用し、json エンコーディングに CIRCE を使用しています。

ベーステーブル:

abstract class BaseTable[T](tag: Tag, name: String) extends Table[T](tag, name) {
  def id = column[Long]("id", O.PrimaryKey, O.AutoInc)
  def createdAt = column[Timestamp]("created_at")
  def updatedAt = column[Timestamp]("updated_at")
  def deletedAt = column[Timestamp]("deleted_at")
}

ベースエンティティ:

trait BaseEntity {
  val id : Long
  def isValid : Boolean = true
}

UserEntity: createdAt がエンコーダ エラーを生成する

case class UserEntity(id: Long, email: String, password: String, createdAt: Timestamp) extends BaseEntity

UserEntity: これは完全に機能します

case class UserEntity(id: Long, email: String, password: String) extends BaseEntity

ユーザーテーブル(スリック):

object UserTables {

  class UserTable(tag : Tag) extends BaseTable[UserEntity](tag, "users") {
    def name = column[String]("name")
    def password = column[String]("password")
    def * = (id, name, password) <> (UserEntity.tupled, UserEntity.unapply)
  }

  implicit val accountsTableQ : TableQuery[UserTable] = TableQuery[UserTable]
}

コードに何か不足していますか? どんな助けでも大歓迎です。

4

1 に答える 1

15

次のようなカスタム エンコーダーとデコーダーをコードに使用する必要があります。

  implicit val TimestampFormat : Encoder[Timestamp] with Decoder[Timestamp] = new Encoder[Timestamp] with Decoder[Timestamp] {
    override def apply(a: Timestamp): Json = Encoder.encodeLong.apply(a.getTime)

    override def apply(c: HCursor): Result[Timestamp] = Decoder.decodeLong.map(s => new Timestamp(s)).apply(c)
  }

タイムスタンプをエンコード/デコードするために必要なコードにこの値を入れます。たとえば、オブジェクトに配置し、必要な場所にオブジェクトをインポートできます。

于 2017-01-05T16:44:02.487 に答える