Skip to content

Commit

Permalink
Add count() method support (#72)
Browse files Browse the repository at this point in the history
  • Loading branch information
YulimitBreak authored Oct 19, 2022
1 parent c9ca9d5 commit b3ab7a4
Show file tree
Hide file tree
Showing 5 changed files with 27 additions and 0 deletions.
3 changes: 3 additions & 0 deletions core/src/jsMain/kotlin/Index.kt
Original file line number Diff line number Diff line change
Expand Up @@ -18,4 +18,7 @@ public class Index internal constructor(

override fun requestOpenKeyCursor(query: Key?, direction: Cursor.Direction): Request<IDBCursor?> =
Request(index.openKeyCursor(query?.toJs(), direction.constant))

override fun requestCount(query: Key?): Request<Int> =
Request(index.count(query?.toJs()))
}
3 changes: 3 additions & 0 deletions core/src/jsMain/kotlin/ObjectStore.kt
Original file line number Diff line number Diff line change
Expand Up @@ -18,4 +18,7 @@ public class ObjectStore internal constructor(

override fun requestOpenKeyCursor(query: Key?, direction: Cursor.Direction): Request<IDBCursor?> =
Request(objectStore.openKeyCursor(query?.toJs(), direction.constant))

override fun requestCount(query: Key?): Request<Int> =
Request(objectStore.count(query?.toJs()))
}
1 change: 1 addition & 0 deletions core/src/jsMain/kotlin/Queryable.kt
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,5 @@ public sealed class Queryable {
internal abstract fun requestGetAll(query: Key?): Request<Array<dynamic>>
internal abstract fun requestOpenCursor(query: Key?, direction: Cursor.Direction): Request<IDBCursorWithValue?>
internal abstract fun requestOpenKeyCursor(query: Key?, direction: Cursor.Direction): Request<IDBCursor?>
internal abstract fun requestCount(query: Key?): Request<Int>
}
10 changes: 10 additions & 0 deletions core/src/jsMain/kotlin/Transaction.kt
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,16 @@ public open class Transaction internal constructor(
}
}

public suspend fun Queryable.count(query: Key? = null): Int {
val request = requestCount(query).request
return request.onNextEvent("success", "error") { event ->
when (event.type) {
"error" -> throw ErrorEventException(event)
else -> request.result
}
}
}

public fun ObjectStore.index(name: String): Index =
Index(objectStore.index(name))
}
Expand Down
10 changes: 10 additions & 0 deletions core/src/jsTest/kotlin/Samples.kt
Original file line number Diff line number Diff line change
Expand Up @@ -58,5 +58,15 @@ class Samples {
.first { it.age < 32 }
}
assertEquals("Charlie", charlie.name)

val count = database.transaction("customers") {
objectStore("customers").count()
}
assertEquals(4, count)

val countBelowThirtyTwo = database.transaction("customers") {
objectStore("customers").index("age").count(upperBound(32))
}
assertEquals(2, countBelowThirtyTwo)
}
}

0 comments on commit b3ab7a4

Please sign in to comment.