Advertisement
mitrakov

Circe Meta for jsonb PostgreSQL

Mar 26th, 2019
371
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 1.27 KB | None | 0 0
  1. // Option 1 (Meta[Json]):
  2. trait JsonMeta {
  3.   import io.circe.syntax._
  4.  
  5.   implicit val JsonMeta: Meta[Json] =
  6.     Meta
  7.       .other[PGobject]("jsonb")
  8.       .xmap[Json](
  9.         a => parse(a.getValue).leftMap[Json](e => throw e).merge,
  10.         a => {
  11.           val o = new PGobject
  12.           o.setType("jsonb")
  13.           o.setValue(a.pretty(Printer.noSpaces.copy(dropNullValues = true)))
  14.           o
  15.         }
  16.       )
  17.  
  18.   def codecMeta[A: Encoder: Decoder: TypeTag]: Meta[A] =
  19.     Meta[Json].xmap[A](_.as[A].fold[A](throw _, identity), _.asJson)
  20. }
  21.  
  22.  
  23.  
  24. // Option 2 (Get/Put):
  25. import doobie.util.{Get, Put, Meta}
  26. import org.postgresql.util.PGobject
  27. import io.circe.parser.parse
  28. import io.circe.Json
  29.  
  30. trait JsonMeta {
  31.   import io.circe.syntax._
  32.   import cats.implicits._
  33.  
  34.   implicit val jsonMeta: Meta[Json] =
  35.     Meta.Advanced.other[PGobject]("json").timap[Json](
  36.       a => parse(a.getValue).leftMap[Json](e => throw e).merge)(
  37.       a => {
  38.         val o = new PGobject
  39.         o.setType("json")
  40.         o.setValue(a.noSpaces)
  41.         o
  42.       }
  43.     )
  44. }
  45.  
  46. trait SettingMeta extends JsonMeta {
  47.   implicit val settingGet: Get[Setting] = Get[Json].tmap(_.as[Setting].toOption.get)
  48.   implicit val settingPut: Put[Setting] = Put[Json].tcontramap(_.asJson)
  49. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement