Skip to content

Commit

Permalink
Ensure version files are created at same path as store
Browse files Browse the repository at this point in the history
Addresses #99
  • Loading branch information
JanTie committed Apr 30, 2024
1 parent 2603c55 commit 106a2de
Showing 1 changed file with 7 additions and 7 deletions.
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package io.github.xxfast.kstore.file.extensions

import io.github.xxfast.kstore.KStore
import io.github.xxfast.kstore.Codec
import io.github.xxfast.kstore.KStore
import io.github.xxfast.kstore.file.utils.FILE_SYSTEM
import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.KSerializer
Expand All @@ -16,15 +16,14 @@ import okio.Path
import okio.Path.Companion.toPath
import okio.buffer
import okio.use

import kotlinx.serialization.json.okio.decodeFromBufferedSource as decode
import kotlinx.serialization.json.okio.encodeToBufferedSink as encode

/**
* Creates a store with a versioned encoder and decoder
* Note: An additional file will be written to manage metadata on the same path with `.version` suffix
*
* @param filePath path to the file that is managed by this store
* @param file path to the file that is managed by this store
* @param default returns this value if the file is not found. defaults to null
* @param enableCache maintain a cache. If set to false, it always reads from disk
* @param json Serializer to use. Defaults serializer ignores unknown keys and encodes the defaults
Expand All @@ -38,9 +37,10 @@ public inline fun <reified T : @Serializable Any> storeOf(
default: T? = null,
enableCache: Boolean = true,
json: Json = Json { ignoreUnknownKeys = true; encodeDefaults = true },
versionPath: Path = "$file.version".toPath(), // TODO: Save to file metadata instead
noinline migration: Migration<T> = DefaultMigration(default),
): KStore<T> {
val codec: Codec<T> = VersionedCodec(file, version, json, json.serializersModule.serializer(), migration)
val codec: Codec<T> = VersionedCodec(file, version, json, json.serializersModule.serializer(), migration, versionPath)
return KStore(default, enableCache, codec)
}

Expand All @@ -50,14 +50,14 @@ public fun <T> DefaultMigration(default: T?): Migration<T> = { _, _ -> default }
public typealias Migration<T> = (version: Int?, JsonElement?) -> T?

@OptIn(ExperimentalSerializationApi::class)
public class VersionedCodec<T: @Serializable Any>(
public class VersionedCodec<T : @Serializable Any>(
private val file: Path,
private val version: Int = 0,
private val json: Json,
private val serializer: KSerializer<T>,
private val migration: Migration<T>,
): Codec<T> {
private val versionPath: Path = "$${file.name}.version".toPath() // TODO: Save to file metadata instead
private val versionPath: Path = "$file.version".toPath(), // TODO: Save to file metadata instead
) : Codec<T> {

override suspend fun decode(): T? =
try {
Expand Down

0 comments on commit 106a2de

Please sign in to comment.