commonMain.io.github.jan.supabase.serializer.MoshiSerializer.kt Maven / Gradle / Ivy
package io.github.jan.supabase.serializer
import com.squareup.moshi.Moshi
import com.squareup.moshi.adapter
import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
import io.github.jan.supabase.SupabaseSerializer
import kotlin.reflect.KType
/**
* A [SupabaseSerializer] that uses moshi
*/
class MoshiSerializer(
private val moshi: Moshi = Moshi.Builder().addLast(KotlinJsonAdapterFactory()).build()
) : SupabaseSerializer {
@OptIn(ExperimentalStdlibApi::class)
override fun encode(type: KType, value: T): String = moshi.adapter(type).toJson(value)
@OptIn(ExperimentalStdlibApi::class)
override fun decode(type: KType, value: String): T {
val adapter = moshi.adapter(type)
return adapter.fromJson(value) ?: error("Failed to decode $value")
}
}