dokar3 / quickjs-kt

A QuickJS binding for idiomatic Kotlin, with Async/DSL/ES Modules support.
Apache License 2.0
31 stars 3 forks source link

Add type converter #86

Closed dokar3 closed 1 month ago

dokar3 commented 1 month ago

Based on the proposal in #82, a new TypeConverter API will be added to support custom types on the function parameters and returns.

interface TypeConverter<Source : Any?, Target : Any?> {
    val sourceType: KClass<*>
    val targetType: KClass<*>

    fun convertToTarget(value: Source): Target
    fun convertToSource(value: Target): Source? = null
}

Here is a quick demo of the new TypeConverter API:

import com.dokar.quickjs.conveter.SerializableConverter
// For moshi
import com.dokar.quickjs.conveter.JsonClassConverter

@kotlinx.serialization.Serializable
// For moshi
@com.squareup.moshi.JsonClass(generateAdapter = true)
data class FetchParams(val url: String, val method: String)

quickJs {
    addTypeConverters(SerializableConverter<FetchParams>())
    // For moshi
    addTypeConverters(JsonClassConverter<FetchParams>())

    asyncFunction<FetchParams, String>("fetch") {
        // Use the typed fetch params
        val (url, method) = it
        TODO()
    }

    val result = evaluate<String>(
        """await fetch({ url: "https://example.com", method: "GET" })"""
    )
}