Code Monkey home page Code Monkey logo

Comments (4)

miguelalexteixeira avatar miguelalexteixeira commented on July 17, 2024

Can you provide more detail about what you're trying to do? What's the structure of the data you're trying to serialize?

from kmongo.

Astridalia avatar Astridalia commented on July 17, 2024

Parsing from generics?

open class MongoDBStorage<T : Any>(clazz: Class<T>, databaseName: String, collectionName: String) : Storage<T> {
    private val client = KMongo.createClient(
        MongoClientSettings.builder()
            .uuidRepresentation(UuidRepresentation.STANDARD)
            .build()
    )


    private val database = client.getDatabase(databaseName)
    private val collection = database.getCollection(collectionName, clazz)


    override fun add(id: Id<T>, entity: T) {
        // Perform the update operation using MongoDB driver
        collection.updateOneById(id, entity, UpdateOptions().upsert(true))
    }


    override fun get(id: Id<T>): T? {
        return collection.findOneById(id)
    }

    override fun getAll(): List<T> {
        return collection.find().toList()
    }

    override fun remove(id: Id<T>) {
        collection.deleteOneById(id)
    }
}

from kmongo.

miguelalexteixeira avatar miguelalexteixeira commented on July 17, 2024

Sorry it took me awhile to respond. This works for me (using org.litote.kmongo:kmongo-coroutine-serialization:4.9.0)

Entity:

@Serializable
public data class UserEntity(
    @Contextual
    @SerialName("_id")
    val id: Id<UserEntity> = newId(),

    @SerialName("first_name")
    val firstName: String,

    @SerialName("last_name")
    val lastName: String
)

Repository:

public interface GenericRepository<T> {
    public suspend fun add(id: Id<T>, entity: T)

    public suspend fun get(id: Id<T>): T?
}

internal class MongoGenericRepository<T: Any>(
    private val kMongoDatabase: CoroutineDatabase,
    private val collectionName: String,
    private val clazz: Class<T>
) : GenericRepository<T> {

    private val collection: CoroutineCollection<T> by lazy {
        kMongoDatabase.database.getCollection(collectionName, clazz).coroutine
    }

    override suspend fun get(id: Id<T>): T? {
        return collection.findOneById(id)
    }

    override suspend fun add(id: Id<T>, entity: T) {
        collection.updateOneById(id, entity, UpdateOptions().upsert(true))
    }
}

I'm assuming that you'll only need to (de)serialize the same entity for a given collection, i.e. only UserEntity instances in the collection users.

from kmongo.

miguelalexteixeira avatar miguelalexteixeira commented on July 17, 2024

If you need to store different entities under the same collection, then you'll need to include a type discriminator in the resulting BSON, so that kotlinx-serialization knows how to deserialize it. This can be achieved through either closed or open polymorphism.

In case you go with open polymorphism, you can call registerModule(serializersModule) to register your custom SerializersModule with KMongo.

You can also further configure the serialization through the global configuration property. E.g.:

configuration = configuration.copy(
    encodeDefaults = false,
    classDiscriminator = SchemaRegistry.TYPE_DISCRIMINATOR
)

from kmongo.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.