Litote / kmongo

[deprecated] KMongo - a Kotlin toolkit for Mongo
https://litote.org/kmongo/
Apache License 2.0
781 stars 75 forks source link

How to register custom kmongo codec in kotlin? #398

Closed urosjarc closed 1 year ago

urosjarc commented 1 year ago

I want to create custom codec for DateTimePeriod...

open class DateTimePeriodCodec : Codec<DateTimePeriod> {

    override fun getEncoderClass(): Class<DateTimePeriod> = DateTimePeriod::class.java

    override fun encode(writer: BsonWriter, value: DateTimePeriod, encoderContext: EncoderContext) {
        writer.writeStartDocument()
        writer.writeInt32("LOL", value.years)
        writer.writeEndDocument()
    }

    override fun decode(reader: BsonReader, decoderContext: DecoderContext): DateTimePeriod {
        return DateTimePeriod(
            years = reader.readInt32("LOL")
        )
    }
}

And then register my custom codec before creating client like it says in documentation...

data class Test(val period: DateTimePeriod)

fun main() {
    val DB_URL = "mongodb://localhost:27017"
    val DB_NAME = "programerski-klub"

    ObjectMappingConfiguration.addCustomCodec(codec = DateTimePeriodCodec())

    val client = KMongo.createClient(DB_URL)
    val db = client.getDatabase(DB_NAME)

    db.getCollection<Test>().save(
        Test(DateTimePeriod(months = 20))
    )
}

But custom codec is not being used by the kmongo :( ...

mervyn-mccreight commented 1 year ago

Which mapping-engine variant of KMongo are you using? Jackson, KotlinX-serialization or native?

Here is how to differentiate between them: https://litote.org/kmongo/quick-start/#object-mapping-engine

As far as I understand the documentation different steps need to be done to add a custom codec/jackson-module/serializer, you can read this here:

urosjarc commented 1 year ago

I have used jackson, but soon I realized that jackson is giving me so much problems on ktor server that I joust gave up and use kotlinx-serialization...