frank
01/07/2022, 6:35 PMinline fun <reified T> getCollection(collection: String): MongoCollection<T> {
return database.getCollection(collection, T::class.java)
}
Full Code:
open class Connection<T> {
constructor(){
startMongoDB()
}
val client by lazy { KMongo.createClient() }
val database by lazy { getDB() }
fun getDB(): MongoDatabase {
return client.getDatabase(DB_NAME)
}
inline fun <reified T> getCollection(collection: String): MongoCollection<T> {
return database.getCollection(collection, T::class.java)
}
private fun startMongoDB() {
client
database
}
}
Klitos Kyriacou
01/10/2022, 10:17 AMStephan Schroeder
01/10/2022, 11:04 AMclass Connection {
private val client = KMongo.createClient()
val database = client.getDatabase(DB_NAME)
}
inline fun <reified T> Connection.getCollection(collection: String): MongoCollection<T> =
this.database.getCollection(collection, T::class.java)
and there is a point to be made that maybe the function should be called directly on Database
instead of on Connection
, so maybe even
inline fun <reified T> Database.getCollection(collection: String): MongoCollection<T> =
this.getCollection(collection, T::class.java)
frank
01/11/2022, 12:40 AMbut what is the point of those two lazily constructed properties which you construct in the class's constructor (and therefore are not really lazy at all)?
I don't even think Connection needs to be generic or openThx, for the tips. Yes, I already had some corrected in my second revision of the code.
class Connection {
private val client = KMongo.createClient().coroutine
val database = client.getDatabase(DB_NAME)
val session = GlobalScope.async(start = CoroutineStart.LAZY) { client.startSession() }
inline fun <reified T : Any> getCollection(collection: String): CoroutineCollection<T> {
return database.getCollection(collection)
}
}