Skip to content

Instantly share code, notes, and snippets.

@ShahOdin
Last active July 3, 2019 10:21
Show Gist options
  • Select an option

  • Save ShahOdin/e1a87ccf67dafd378a9cbe1a7fbfc30f to your computer and use it in GitHub Desktop.

Select an option

Save ShahOdin/e1a87ccf67dafd378a9cbe1a7fbfc30f to your computer and use it in GitHub Desktop.
my failed attempt at implementing a meta instance for tsrange
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
}
)
}
@ShahOdin

ShahOdin commented Jul 2, 2019

Copy link
Copy Markdown
Author

ignore the teimap. It's a syntax extension: a combination of temap and contramap.

@nigredo-tori

Copy link
Copy Markdown

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.

@ShahOdin

ShahOdin commented Jul 3, 2019

Copy link
Copy Markdown
Author

now working.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment