-
Notifications
You must be signed in to change notification settings - Fork 168
/
Copy pathdatabase.kt
266 lines (208 loc) · 10.3 KB
/
database.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
/*
* Copyright (c) 2020 GitLive Ltd. Use of this source code is governed by the Apache 2.0 license.
*/
package dev.gitlive.firebase.database
import cocoapods.FirebaseDatabase.*
import cocoapods.FirebaseDatabase.FIRDataEventType.*
import dev.gitlive.firebase.Firebase
import dev.gitlive.firebase.FirebaseApp
import dev.gitlive.firebase.database.ChildEvent.Type
import dev.gitlive.firebase.database.ChildEvent.Type.*
import dev.gitlive.firebase.decode
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.FlowPreview
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.flow.callbackFlow
import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.flow.produceIn
import kotlinx.coroutines.selects.select
import kotlinx.serialization.DeserializationStrategy
import kotlinx.serialization.KSerializer
import kotlinx.serialization.SerializationStrategy
import platform.Foundation.*
import kotlin.collections.component1
import kotlin.collections.component2
@PublishedApi
internal inline fun <reified T> encode(value: T, shouldEncodeElementDefault: Boolean) =
dev.gitlive.firebase.encode(value, shouldEncodeElementDefault, FIRServerValue.timestamp())
internal fun <T> encode(strategy: SerializationStrategy<T> , value: T, shouldEncodeElementDefault: Boolean): Any? =
dev.gitlive.firebase.encode(strategy, value, shouldEncodeElementDefault, FIRServerValue.timestamp())
actual val Firebase.database
by lazy { FirebaseDatabase(FIRDatabase.database()) }
actual fun Firebase.database(url: String) =
FirebaseDatabase(FIRDatabase.databaseWithURL(url))
actual fun Firebase.database(app: FirebaseApp) =
FirebaseDatabase(FIRDatabase.databaseForApp(app.ios))
actual fun Firebase.database(app: FirebaseApp, url: String) =
FirebaseDatabase(FIRDatabase.databaseForApp(app.ios, url))
actual class FirebaseDatabase internal constructor(val ios: FIRDatabase) {
actual fun reference(path: String) =
DatabaseReference(ios.referenceWithPath(path), ios.persistenceEnabled)
actual fun reference() =
DatabaseReference(ios.reference(), ios.persistenceEnabled)
actual fun setPersistenceEnabled(enabled: Boolean) {
ios.persistenceEnabled = enabled
}
actual fun setLoggingEnabled(enabled: Boolean) =
FIRDatabase.setLoggingEnabled(enabled)
actual fun useEmulator(host: String, port: Int) =
ios.useEmulatorWithHost(host, port.toLong())
}
fun Type.toEventType() = when(this) {
ADDED -> FIRDataEventTypeChildAdded
CHANGED -> FIRDataEventTypeChildChanged
MOVED -> FIRDataEventTypeChildMoved
REMOVED -> FIRDataEventTypeChildRemoved
}
actual open class Query internal constructor(
open val ios: FIRDatabaseQuery,
val persistenceEnabled: Boolean
) {
actual fun orderByKey() = Query(ios.queryOrderedByKey(), persistenceEnabled)
actual fun orderByValue() = Query(ios.queryOrderedByValue(), persistenceEnabled)
actual fun orderByChild(path: String) = Query(ios.queryOrderedByChild(path), persistenceEnabled)
actual fun startAt(value: String, key: String?) = Query(ios.queryStartingAtValue(value, key), persistenceEnabled)
actual fun startAt(value: Double, key: String?) = Query(ios.queryStartingAtValue(value, key), persistenceEnabled)
actual fun startAt(value: Boolean, key: String?) = Query(ios.queryStartingAtValue(value, key), persistenceEnabled)
actual fun endAt(value: String, key: String?) = Query(ios.queryEndingAtValue(value, key), persistenceEnabled)
actual fun endAt(value: Double, key: String?) = Query(ios.queryEndingAtValue(value, key), persistenceEnabled)
actual fun endAt(value: Boolean, key: String?) = Query(ios.queryEndingAtValue(value, key), persistenceEnabled)
actual fun limitToFirst(limit: Int) = Query(ios.queryLimitedToFirst(limit.toULong()), persistenceEnabled)
actual fun limitToLast(limit: Int) = Query(ios.queryLimitedToLast(limit.toULong()), persistenceEnabled)
actual fun equalTo(value: String, key: String?) = Query(ios.queryEqualToValue(value, key), persistenceEnabled)
actual fun equalTo(value: Double, key: String?) = Query(ios.queryEqualToValue(value, key), persistenceEnabled)
actual fun equalTo(value: Boolean, key: String?) = Query(ios.queryEqualToValue(value, key), persistenceEnabled)
actual val valueEvents get() = callbackFlow<DataSnapshot> {
val handle = ios.observeEventType(
FIRDataEventTypeValue,
withBlock = { snapShot ->
trySend(DataSnapshot(snapShot!!))
}
) { close(DatabaseException(it.toString(), null)) }
awaitClose { ios.removeObserverWithHandle(handle) }
}
actual fun childEvents(vararg types: Type) = callbackFlow<ChildEvent> {
val handles = types.map { type ->
ios.observeEventType(
type.toEventType(),
andPreviousSiblingKeyWithBlock = { snapShot, key ->
trySend(ChildEvent(DataSnapshot(snapShot!!), type, key))
}
) { close(DatabaseException(it.toString(), null)) }
}
awaitClose {
handles.forEach { ios.removeObserverWithHandle(it) }
}
}
override fun toString() = ios.toString()
}
actual class DatabaseReference internal constructor(
override val ios: FIRDatabaseReference,
persistenceEnabled: Boolean
): Query(ios, persistenceEnabled) {
actual val key get() = ios.key
actual fun child(path: String) = DatabaseReference(ios.child(path), persistenceEnabled)
actual fun push() = DatabaseReference(ios.childByAutoId(), persistenceEnabled)
actual fun onDisconnect() = OnDisconnect(ios, persistenceEnabled)
actual suspend inline fun <reified T> setValue(value: T?, encodeDefaults: Boolean) {
ios.await(persistenceEnabled) { setValue(encode(value, encodeDefaults), it) }
}
actual suspend fun <T> setValue(strategy: SerializationStrategy<T>, value: T, encodeDefaults: Boolean) {
ios.await(persistenceEnabled) { setValue(encode(strategy, value, encodeDefaults), it) }
}
@Suppress("UNCHECKED_CAST")
actual suspend fun updateChildren(update: Map<String, Any?>, encodeDefaults: Boolean) {
ios.await(persistenceEnabled) { updateChildValues(encode(update, encodeDefaults) as Map<Any?, *>, it) }
}
actual suspend fun removeValue() {
ios.await(persistenceEnabled) { removeValueWithCompletionBlock(it) }
}
actual suspend fun <T> runTransaction(strategy: KSerializer<T>, transactionUpdate: (currentData: T) -> T): DataSnapshot {
val deferred = CompletableDeferred<DataSnapshot>()
ios.runTransactionBlock(
block = { firMutableData ->
firMutableData?.value = firMutableData?.value?.let {
transactionUpdate(decode(strategy, firMutableData.value))
}
FIRTransactionResult.successWithValue(firMutableData!!)
},
andCompletionBlock = { error, _, snapshot ->
if (error != null) {
deferred.completeExceptionally(DatabaseException(error.toString(), null))
} else {
deferred.complete(DataSnapshot(snapshot!!))
}
},
withLocalEvents = false
)
return deferred.await()
}
}
@Suppress("UNCHECKED_CAST")
actual class DataSnapshot internal constructor(val ios: FIRDataSnapshot) {
actual val exists get() = ios.exists()
actual val key: String? get() = ios.key
actual inline fun <reified T> value() =
decode<T>(value = ios.value)
actual fun <T> value(strategy: DeserializationStrategy<T>) =
decode(strategy, ios.value)
actual fun child(path: String) = DataSnapshot(ios.childSnapshotForPath(path))
actual val children: Iterable<DataSnapshot> get() = ios.children.allObjects.map { DataSnapshot(it as FIRDataSnapshot) }
}
actual class OnDisconnect internal constructor(
val ios: FIRDatabaseReference,
val persistenceEnabled: Boolean
) {
actual suspend fun removeValue() {
ios.await(persistenceEnabled) { onDisconnectRemoveValueWithCompletionBlock(it) }
}
actual suspend fun cancel() {
ios.await(persistenceEnabled) { cancelDisconnectOperationsWithCompletionBlock(it) }
}
actual suspend inline fun <reified T> setValue(value: T, encodeDefaults: Boolean) {
ios.await(persistenceEnabled) { onDisconnectSetValue(encode(value, encodeDefaults), it) }
}
actual suspend fun <T> setValue(strategy: SerializationStrategy<T>, value: T, encodeDefaults: Boolean) {
ios.await(persistenceEnabled) { onDisconnectSetValue(encode(strategy, value, encodeDefaults), it) }
}
@Suppress("UNCHECKED_CAST")
actual suspend fun updateChildren(update: Map<String, Any?>, encodeDefaults: Boolean) {
ios.await(persistenceEnabled) { onDisconnectUpdateChildValues(update.mapValues { (_, it) -> encode(it, encodeDefaults) } as Map<Any?, *>, it) }
}
}
actual class DatabaseException actual constructor(message: String?, cause: Throwable?) : RuntimeException(message, cause)
private suspend inline fun <T, reified R> T.awaitResult(whileOnline: Boolean, function: T.(callback: (NSError?, R?) -> Unit) -> Unit): R {
val job = CompletableDeferred<R?>()
function { error, result ->
if(error == null) {
job.complete(result)
} else {
job.completeExceptionally(DatabaseException(error.toString(), null))
}
}
return job.run { if(whileOnline) awaitWhileOnline() else await() } as R
}
suspend inline fun <T> T.await(whileOnline: Boolean, function: T.(callback: (NSError?, FIRDatabaseReference?) -> Unit) -> Unit) {
val job = CompletableDeferred<Unit>()
function { error, _ ->
if(error == null) {
job.complete(Unit)
} else {
job.completeExceptionally(DatabaseException(error.toString(), null))
}
}
job.run { if(whileOnline) awaitWhileOnline() else await() }
}
@FlowPreview
suspend fun <T> CompletableDeferred<T>.awaitWhileOnline(): T = coroutineScope {
val notConnected = Firebase.database
.reference(".info/connected")
.valueEvents
.filter { !it.value<Boolean>() }
.produceIn(this)
select<T> {
onAwait { it.also { notConnected.cancel() } }
notConnected.onReceive { throw DatabaseException("Database not connected", null) }
}
}