Created
August 27, 2020 10:45
-
-
Save thinkharderdev/1f6ffd0b9b2768bea869be73bb63ba47 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.sql.Types | |
import io.circe._ | |
import io.getquill.context.jdbc.JdbcContextBase | |
import org.postgresql.util.PGobject | |
import doobie._ | |
import doobie.implicits._ | |
import doobie.postgres.implicits._ | |
sealed trait IdentifierType | |
case object IdentifierType { | |
case object Email extends IdentifierType | |
case object Mdn extends IdentifierType | |
case object Username extends IdentifierType | |
def toString(identifierType: IdentifierType): String = | |
identifierType match { | |
case Email => "EMAIL" | |
case Mdn => "MDN" | |
case Username => "USERNAME" | |
} | |
def fromString(value: String): Option[IdentifierType] = { | |
Option(value).collect { | |
case "EMAIL" => Email | |
case "MDN" => Mdn | |
case "USERNAME" => Username | |
} | |
} | |
implicit val identifierTypeMeta: Meta[IdentifierType] = | |
pgEnumStringOpt("identifier_type", IdentifierType.fromString, IdentifierType.toString) | |
} | |
trait MyQuillExtensions { self: JdbcContextBase[_, _] => | |
implicit val jsonDecoder: JdbcDecoder[Json] = decoder { (index, row) => | |
parser.parse(row.getObject(index).toString) match { | |
case Left(err) => | |
throw new IllegalArgumentException(s"Invalid JSON: ${err.message}") | |
case Right(json) => json | |
} | |
} | |
implicit val jsonEncoder: JdbcEncoder[Json] = { | |
encoder( | |
Types.OTHER, | |
(index, value, row) => { | |
val pgObject = new PGobject() | |
pgObject.setType("jsonb") | |
pgObject.setValue(value.toString()) | |
row.setObject(index, pgObject) | |
} | |
) | |
} | |
implicit val encodeIdentifierType: JdbcEncoder[IdentifierType] = { | |
encoder( | |
Types.OTHER, | |
(index, value, row) => { | |
val pgObject = new PGobject() | |
pgObject.setType("identifier_type") | |
pgObject.setValue(IdentifierType.toString(value)) | |
row.setObject(index, pgObject) | |
} | |
) | |
} | |
implicit val decodeIdetifierType: JdbcDecoder[IdentifierType] = decoder { (index, row) => | |
IdentifierType | |
.fromString(row.getObject(index).toString) | |
.getOrElse( | |
throw new IllegalArgumentException(s"Invalid identifier type: ${row.getString(index)}") | |
) | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment