Skip to content

Commit

Permalink
Fix .temp file not found when deleting store (#135)
Browse files Browse the repository at this point in the history
* Fix .temp file not found issue while deleting.

---------

Co-authored-by: Isuru Rajapakse <[email protected]>
  • Loading branch information
SultanArshad and xxfast authored Nov 6, 2024
1 parent 1fc0005 commit 211141f
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 7 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -61,11 +61,15 @@ public class FileCodec<T : @Serializable Any>(
*/
@OptIn(ExperimentalSerializationApi::class)
override suspend fun encode(value: T?) {
if (value == null) {
SystemFileSystem.delete(file, mustExist = false)
return
}

try {
if (value != null) SystemFileSystem.sink(tempFile).buffered().use { json.encode(serializer, value, it) }
else SystemFileSystem.delete(tempFile)
SystemFileSystem.sink(tempFile).buffered().use { json.encode(serializer, value, it) }
} catch (e: Throwable) {
SystemFileSystem.delete(tempFile)
SystemFileSystem.delete(tempFile, mustExist = false)
throw e
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,12 @@ class FileCodecTests {

@OptIn(ExperimentalSerializationApi::class)
private var stored: List<Pet>?
get() = SystemFileSystem.source(Path(FILE_PATH))
.buffered()
.use { DefaultJson.decodeFromSource(it) }
get() = if (!SystemFileSystem.exists(Path(FILE_PATH))) null
else {
SystemFileSystem.source(Path(FILE_PATH))
.buffered()
.use { DefaultJson.decodeFromSource(it) }
}

set(value) {
SystemFileSystem.sink(Path(FILE_PATH))
Expand All @@ -33,7 +36,7 @@ class FileCodecTests {

@AfterTest
fun cleanUp() {
SystemFileSystem.delete(Path(FILE_PATH))
SystemFileSystem.delete(Path(FILE_PATH), false)
}

@Test
Expand All @@ -44,6 +47,14 @@ class FileCodecTests {
assertEquals(expect, actual)
}

@Test
fun testEncodeWithNullValue() = runTest {
codec.encode(null)
val expect: List<Pet>? = null
val actual: List<Pet>? = stored
assertEquals(expect, actual)
}

@Test
fun testDecode() = runTest {
stored = listOf(OREO)
Expand Down

0 comments on commit 211141f

Please sign in to comment.