Emil Kantis
06/07/2021, 8:36 PM// Entity
class Client(id: EntityID<Int>) : IntEntity(id) {
companion object : IntEntityClass<Client>(Clients)
// Some code omitted
var tags2: List<String> by jsonStore(Clients.tags)
}
// Delegate provider
inline fun <reified S, T : Comparable<T>> Entity<T>.jsonStore(column: Column<String>) = JsonStore<T, S>(
serializer(),
column,
{ column.lookup() },
{ thisRef, property, value -> column.setValue(thisRef, property, value) }
)
// Delegate
class JsonStore<T : Comparable<T>, S>(
val serializer: KSerializer<S>,
val column: Column<String>,
val lookup: (Column<String>) -> String,
val write: (Entity<T>, KProperty<*>, String) -> Unit
) {
operator fun getValue(thisRef: Any?, property: KProperty<*>): S =
json.decodeFromString(serializer, lookup(column))
operator fun setValue(thisRef: Entity<T>, property: KProperty<*>, value: S) =
write(thisRef, property, json.encodeToString(serializer, value))
}
rnett
06/08/2021, 2:01 AMEntity
, but that's going to be the case anyways).Json
instance a TextFormat
parameter.Emil Kantis
06/08/2021, 12:25 PMjsonStore
to JsonStore
since the column.lookup()
function is defined in Entity
, not accessible outside.. likewise with setValue
rnett
06/08/2021, 8:53 PMthisRef
in the get/setValue functions. You have it now in setValue
, you would just have to change `getValue`'s thisRef
type (which isn't an issue since you can only create the delegate inside of an Entity anyways).Emil Kantis
06/08/2021, 9:03 PMclass JsonStore<T : Comparable<T>, S>(
private val json: Json,
private val serializer: KSerializer<S>,
private val column: Column<String>,
) {
operator fun getValue(thisRef: Entity<T>, property: KProperty<*>): S =
json.decodeFromString(serializer, with(thisRef) { column.lookup() })
operator fun setValue(thisRef: Entity<T>, property: KProperty<*>, value: S) =
with(thisRef) { column.setValue(this, property, json.encodeToString(serializer, value)) }
}
inline fun <T : Comparable<T>, reified S> jsonStore(column: Column<String>, json: Json = Json.Default) = JsonStore<T, S>(
json,
serializer(),
column,
)