KStore icon indicating copy to clipboard operation
KStore copied to clipboard

FeatureRequest: Add the ability to use Indexed DB for JS and WasmJs

Open eygraber opened this issue 1 year ago • 5 comments

Like the title says, it would be nice to back the store in Indexed DB especially because it is async, performs better, and has a higher storage limit.

eygraber avatar Aug 29 '24 06:08 eygraber

Should be doable with a custom codec. Although not sure if it should be part of kstore 🤔

xxfast avatar Sep 01 '24 02:09 xxfast

I made a quick implementation using this indexeddb library. I guess once that is merged I can make a separate repo for providing that Codec. Any particular reason for it not being part of kstore (3rd party dependency, etc...)?

private inline fun <reified T : @Serializable Any> IndexedDbCodec(
  key: String,
  storeName: String,
  json: Json = DefaultJson,
  database: Database,
): IndexedDbCodec<T> = IndexedDbCodec(
  key = key,
  storeName = storeName,
  json = json,
  serializer = json.serializersModule.serializer(),
  database = database,
)

private class IndexedDbCodec<T : @Serializable Any>(
  private val key: String,
  private val storeName: String,
  private val json: Json,
  private val serializer: KSerializer<T>,
  private val database: Database,
) : Codec<T> {
  override suspend fun encode(value: T?) {
    database.writeTransaction(storeName) {
      val store = objectStore(storeName)
      if(value != null) {
        store.put(json.encodeToString(serializer, value).toJsString(), IDBKey(key))
      }
      else {
        store.delete(IDBKey(key))
      }
    }
  }

  override suspend fun decode(): T? = database.transaction(storeName) {
    val store = objectStore(storeName)
    runCatching {
      store.get(IDBKey(key)).unsafeCast<JsString>().toString()
    }.getOrNull()?.let {
      json.decodeFromString(serializer, it)
    }
  }
}

eygraber avatar Sep 02 '24 05:09 eygraber

Hi @eygraber

Thank you so much for the reply.

Any particular reason for it not being part of kstore (3rd party dependency, etc...)?

Yeah basically that. I initially wanted to limit 3rd party libraries down to just the kotlinx-libraries (hence this migration) but I don't see any harm in allowing a separate module for this, perhaps named kstore-indexed-db

Feel free to PR this in to my repo :) you should be able to use kstore-storage module (which uses the storage apis) as a template. I should be able to include those artifacts in the next release

xxfast avatar Sep 03 '24 15:09 xxfast

I'll open one soon. Waiting for a PR to get merged in to the 3rd party library that supports wasm.

eygraber avatar Sep 03 '24 17:09 eygraber

any progress on this?

ApoloApps avatar Oct 23 '24 18:10 ApoloApps