Last active
July 3, 2019 10:21
-
-
Save ShahOdin/e1a87ccf67dafd378a9cbe1a7fbfc30f to your computer and use it in GitHub Desktop.
my failed attempt at implementing a meta instance for tsrange
This file contains 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
case class TimeWindow(from: Instant, until: Instant) | |
implicit def tsrange: Meta[TimeWindow] = { | |
def toString(timeWindow: TimeWindow): String = | |
s"[" + | |
s"${Timestamp.from(timeWindow.from).toString}," + | |
s"${Timestamp.from(timeWindow.until).toString}" + | |
s")" | |
def fromString(s: String): Either[String, TimeWindow] = { | |
(s.take(1), | |
s.drop(1).dropRight(1).replace("\"", "").split(","), | |
s.takeRight(1)) match { | |
case ("[", Array(from, until), ")") => | |
Either.catchOnly[IllegalArgumentException] { | |
TimeWindow(Timestamp.valueOf(from).toInstant, Timestamp.valueOf(until).toInstant) | |
}.leftMap(_.getMessage) | |
case _ => Left(s"failed to parse TimeWindow value: $s") | |
} | |
} | |
Meta.Advanced | |
.other[PGobject]("tsrange") | |
.teimap( | |
pgO => fromString(pgO.getValue) | |
)( | |
timeWindow => { | |
val pgO = new PGobject | |
pgO.setType("tsrange") | |
pgO.setValue(toString(timeWindow)) | |
pgO | |
} | |
) | |
} |
You build a Json string, and then encode that (.noSpaces
), so you end up with extra quotes. Json doesn't help here - I would just add these:
def asString(tw: TimeWindow): String
def fromString(s: String): Option[TimeWindow]
and use them both in Encoder
/Decoder
and Meta
implementations.
Also, I don't think your decoder works. I think you would get an array of four elements there. And the timestamp parsing exceptions are not caught.
now working.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
ignore the
teimap
. It's a syntax extension: a combination oftemap
andcontramap
.