0

I want to create automatically mongo codecs for nested case classes which are big and have many levels of composition.

As a simple example, let's say I want to create codecs for the following classes:

case class Person(name: String, address: Address, birthDate: Date)
case class Address(country: String, city: String, streetAddress: String)

when using the createCodecProvider:

    private val customCodecs = Macros.createCodecProvider[Person]()

    private val javaCodecs = CodecRegistries.fromCodecs(
        new DateCodec())

    private val codecRegistry = fromRegistries(fromProviders(customCodecs),
        javaCodecs,
        DEFAULT_CODEC_REGISTRY)

I'm getting the error:

org.bson.codecs.configuration.CodecConfigurationException: Can't find a codec for class io.equalum.server.alert.Address.

The following way does work:

    private val customCodecs = fromProviders(classOf[Person], classOf[Address])

    private val javaCodecs = CodecRegistries.fromCodecs(
        new DateCodec())

    private val codecRegistry = fromRegistries(customCodecs,
        javaCodecs,
        DEFAULT_CODEC_REGISTRY)

but, of course, this will be very difficult to write and maintain for large case classes.

Or Bar Yaacov
  • 259
  • 3
  • 13
  • 1
    Well... this is what you exactly have to do. You will have to reqgister every case class with codec registry. There is no otherway around it. – sarveshseri Sep 27 '20 at 08:50
  • 1
    You could also have at how such case are handled with [typeclasses](http://reactivemongo.org/releases/1.0/documentation/bson/typeclasses.html) in ReactiveMongo. – cchantep Sep 27 '20 at 11:41

0 Answers0