-
Notifications
You must be signed in to change notification settings - Fork 349
/
Instances.scala
81 lines (64 loc) · 2.14 KB
/
Instances.scala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
// Copyright (c) 2013-2018 Rob Norris and Contributors
// This software is licensed under the MIT License (MIT).
// For more information see LICENSE or https://opensource.org/licenses/MIT
package doobie.postgres.circe
import cats.data.NonEmptyList
import cats.implicits._
import io.circe._
import io.circe.jawn._
import io.circe.syntax._
import doobie.util._
import org.postgresql.util.PGobject
import scala.reflect.runtime.universe.TypeTag
object Instances {
trait JsonbInstances {
implicit val jsonbPut: Put[Json] =
Put.Advanced.other[PGobject](
NonEmptyList.of("jsonb")
).tcontramap{a =>
val o = new PGobject
o.setType("jsonb")
o.setValue(a.noSpaces)
o
}
implicit val jsonbGet: Get[Json] =
Get.Advanced.other[PGobject](
NonEmptyList.of("jsonb")
).tmap(a =>
parse(a.getValue).leftMap[Json](e => throw e).merge
)
def pgEncoderPutT[A: Encoder: TypeTag]: Put[A] =
Put[Json].tcontramap(_.asJson)
def pgEncoderPut[A: Encoder]: Put[A] =
Put[Json].contramap(_.asJson)
def pgDecoderGetT[A: Decoder: TypeTag]: Get[A] =
Get[Json].tmap(json => json.as[A].fold(throw _, identity))
def pgDecoderGet[A: Decoder]: Get[A] =
Get[Json].map(json => json.as[A].fold(throw _, identity))
}
trait JsonInstances {
implicit val jsonPut: Put[Json] =
Put.Advanced.other[PGobject](
NonEmptyList.of("json")
).tcontramap{a =>
val o = new PGobject
o.setType("json")
o.setValue(a.noSpaces)
o
}
implicit val jsonGet: Get[Json] =
Get.Advanced.other[PGobject](
NonEmptyList.of("json")
).tmap(a =>
parse(a.getValue).leftMap[Json](e => throw e).merge
)
def pgEncoderPutT[A: Encoder: TypeTag]: Put[A] =
Put[Json].tcontramap(_.asJson)
def pgEncoderPut[A: Encoder]: Put[A] =
Put[Json].contramap(_.asJson)
def pgDecoderGetT[A: Decoder: TypeTag]: Get[A] =
Get[Json].tmap(json => json.as[A].fold(throw _, identity))
def pgDecoderGet[A: Decoder]: Get[A] =
Get[Json].map(json => json.as[A].fold(throw _, identity))
}
}