slinky
slinky copied to clipboard
Write docs on how to write Reader/Writer instances
Originally reported by @gavares https://gitter.im/shadaj/slinky?at=5bdd414a538a1c1971672c2f
I have anid field that was prematurely optimized to be a long (String in JSON), so I thought I'd post some examples of custom Readers that convert the id field back to an Int:
implicit val strReader: Reader[String] = slinky.readwrite.Reader.stringReader
implicit val fieldsReader: Reader[Fields] = slinky.readwrite.Reader.deriveReader[Fields]
implicit val myReader: Reader[CClass] = s => {
val sd = s.asInstanceOf[js.Dynamic]
CClass(
// would be cool if Reader could take a Dynamic, so to avoid so much asInstanceOf typing
id = strReader.read(sd.id.asInstanceOf[js.Object]).toInt,
fields = fieldsReader.read(sd.fields.asInstanceOf[js.Object])
)
}
Or, a much simpler approach is to just stick with a Long type and use slinky's built-in Reader, since it first casts to a String anyway:
https://github.com/shadaj/slinky/blob/main/readWrite/src/main/scala/slinky/readwrite/CoreReaders.scala#L72