kostya05983
kostya05983

Reputation: 21

How can I easily configure codec?

Framework uses LUUID to store java.util.UUID, but we want to save it in standard UUID format in mongodb. It can be achieved if we configure BsonUUIDCodec with type Standard.

We have already tried to configure codec with make a configuration with bean ReactiveMongoDatabaseFactory. It works, but it's uncomfortable we need also provide database, uri and so on.

Our implementation:

@Bean
    fun mongoFactory(
        environment: ConfigurableEnvironment
    ): ReactiveMongoDatabaseFactory {
        val builder = MongoClientSettings.builder()

        val codecRegistry =
            fromRegistries(fromCodecs(UuidCodec(UuidRepresentation.STANDARD)), getDefaultCodecRegistry())
        builder.codecRegistry(codecRegistry)

        val database = requireNotNull(environment.getProperty(DATABASE_PROPERTY)) { "Database must be specified" }
        val uri = requireNotNull(environment.getProperty(URI_PROPERTY)) { "URI must be specified" }

        val connectionString = if (!uri.contains(database)) {
            "$uri/$database"
        } else {
            uri
        }
        builder.applyConnectionString(ConnectionString(connectionString))

        val mongoClient = MongoClients.create(builder.build())
        return SimpleReactiveMongoDatabaseFactory(mongoClient, database)
    }

We want to provide codec without overriding additional settings such as uri and database and custom configuration of others settings. Any more simple way to configure codec?

Upvotes: 0

Views: 280

Answers (1)

kostya05983
kostya05983

Reputation: 21

It can be done by MongoClientSettingsBuilderCustomizer, something like this.

@Bean
fun customMongoClientSettings(): MongoClientSettingsBuilderCustomizer {
    return MongoClientSettingsBuilderCustomizer {
        val codecRegistry = fromRegistries(
            fromCodecs(UuidCodec(UuidRepresentation.STANDARD)), getDefaultCodecRegistry()
        )
        it.codecRegistry(codecRegistry)
    }
}

Upvotes: 2

Related Questions