Skip to content

Commit

Permalink
add default serializer for documentid + test
Browse files Browse the repository at this point in the history
  • Loading branch information
stashymane committed Jan 4, 2025
1 parent 6b7b3ee commit f1fa404
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package dev.stashy.mongoservices.model

import kotlinx.serialization.Serializable
import kotlin.jvm.JvmInline

/**
Expand All @@ -23,4 +24,5 @@ import kotlin.jvm.JvmInline
* ```
*/
@JvmInline
@Serializable(with = DocumentIdSerializer::class)
value class DocumentId(val value: String)
36 changes: 36 additions & 0 deletions model/src/commonTest/kotlin/DocumentIdSerializationTest.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import dev.stashy.mongoservices.model.DocumentId
import dev.stashy.mongoservices.model.DocumentIdSerializer
import kotlinx.serialization.Contextual
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import kotlinx.serialization.modules.SerializersModule
import kotlinx.serialization.modules.contextual
import kotlin.test.Test
import kotlin.test.assertEquals

class DocumentIdSerializationTest {
private val customJson = Json { serializersModule = SerializersModule { contextual(DocumentIdSerializer) } }

@Serializable
data class TestObj(@SerialName("_id") @Contextual val id: @Contextual DocumentId, val foo: String)

@Test
fun `documentId serialization`() {
val documentId = DocumentId("test")
val serializedDefault = Json.encodeToString(documentId)
val serializedCustom = customJson.encodeToString(documentId)

assertEquals("\"test\"", serializedDefault)
assertEquals("\"test\"", serializedCustom)
}

@Test
fun `contextual documentId inside an object`() {
val documentId = DocumentId("test")
val testObj = TestObj(documentId, "test")

assertEquals(customJson.encodeToString(testObj), Json.encodeToString(testObj))
}
}

0 comments on commit f1fa404

Please sign in to comment.