Skip to content

Instantly share code, notes, and snippets.

@kpmeen
Created May 22, 2016 09:02
Show Gist options
  • Save kpmeen/670809c21c524aa4153173b64f30bdad to your computer and use it in GitHub Desktop.
Save kpmeen/670809c21c524aa4153173b64f30bdad to your computer and use it in GitHub Desktop.
Converting case classes in an HList to reactivemongo based BSONDocuments using Shapeless
import reactivemongo.bson.Macros
import shapeless._
object ToBson extends Poly1 {
import reactivemongo.bson._
implicit def caseClass[E](
implicit
ev: E <:< Product,
gen: Generic.Aux[E, _ <: HList],
writer: BSONWriter[E, _ <: BSONValue]
) =
at[E](e => BSON.write(e))
}
case class Foo(a: String, b: Int)
object Foo {
implicit val fooHandler = Macros.handler[Foo]
}
case class Bar(c: Boolean, d: Double)
object Bar {
implicit val barHandler = Macros.handler[Bar]
}
val h = Foo("bla", 123) :: Bar(false, 12.0) :: HNil
h map ToBson // res0: shapeless.::[reactivemongo.bson.BSONValue,shapeless.::[reactivemongo.bson.BSONValue,shapeless.HNil]] = BSONDocument(<non-empty>) :: BSONDocument(<non-empty>) :: HNil
/*
Then, by converting the HList to a traversable and initialising a BSONArray, the pretty print will yield this result:
{
0: {
a: "bla",
b: BSONInteger(123)
},
1: {
c: BSONBoolean(false),
d: BSONDouble(12.0)
}
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment