How to encode / decode timestamp for json in circus?

When using circe in slick to get data in json, I could get data without date fields (Timestamp/DateTime) in Entities. But when I use the Timestamp fields in Entities, an error occurs:

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

Here is the code I used for Slick Entities and using CIRCE for json encoding.

BaseTable:

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

BaseEntity:

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

UserEntity: createdAt generates an encoder error

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

UserEntity: works great

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

UserTable (Slick):

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

Am I missing something in the code? Any help would be greatly appreciated.

+6
source share
1 answer

You should use your own code and decoder for your code, something like this:

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

Put this val in any code needed to encode / decode timestamps. For example, you can put it in an object and import the object where necessary.

+6
source

Source: https://habr.com/ru/post/1013711/


All Articles