Trying to create item in Cosmos (document) DB with Kotlin (Ktor)
using implementation("com.azure:azure-cosmos:4.41.0")
@Serializable
data class Session(
var id: String? = null,
var name: String,
var city: String,
)
override suspend fun createSession(session: Session): Response? {
try {
session.id = UUID.randomUUID().toString()
val response = sessionContainerRef.createItem(session)
return Response (
response.item.id!!,
response.item.name
)
} catch (ex: Exception) {
throw(ex)
}
}
The code creates a record in DB but the item in response object is always null. I get the error message:
Cannot invoke "model.Session.getId()" because the return value of "com.azure.cosmos.models.CosmosItemResponse.getItem()" is null
What am I missing? How to fix this? Thnx in advance
CosmosClient contentResponseOnWriteEnabled flag should be set true, and consistencyLevel should be set as 'SESSION'. Following code snippet fixed my problem.
init {
val client = CosmosClientBuilder()
.endpoint(config.endpoint)
.key(config.primaryKey)
.consistencyLevel(ConsistencyLevel.SESSION)
.contentResponseOnWriteEnabled(true)
.buildClient();
}