-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathFirestoreClient.swift
More file actions
932 lines (831 loc) · 31.6 KB
/
Copy pathFirestoreClient.swift
File metadata and controls
932 lines (831 loc) · 31.6 KB
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
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
//
// FirestoreClient.swift
//
// Created by Fumiya Tanaka on 2020/11/11.
//
import FirebaseFirestore
import Foundation
public protocol FirestoreModel: Codable, Identifiable {
static var collectionName: String { get }
var id: String? { get }
var ref: DocumentReference? { get set }
var createdAt: Timestamp? { get set }
var updatedAt: Timestamp? { get set }
static func generateDocumentReference(firestore: Firestore?, id: String?) -> DocumentReference
}
extension FirestoreModel {
public var id: String? {
ref?.documentID
}
public static func generateDocumentReference(firestore: Firestore?, id: String?) -> DocumentReference {
let firestore = firestore ?? Firestore.firestore()
if let id {
return firestore.collection(Self.collectionName).document(id)
}
return firestore.collection(Self.collectionName).document()
}
}
public protocol SubCollectionModel: FirestoreModel {
static var parentCollectionName: String { get }
}
public protocol FirestoreQueryFilter {
var fieldPath: String { get }
func build<Model: FirestoreModel>(type: Model.Type) -> Query
func build(from: Query) -> Query
}
public struct FirestoreQueryOrder {
public var fieldPath: String
public var isAscending: Bool
public init(fieldPath: String, isAscending: Bool) {
self.fieldPath = fieldPath
self.isAscending = isAscending
}
public func build(from: Query) -> Query {
from.order(by: fieldPath, descending: !isAscending)
}
}
public struct FirestoreRangeFilter<Value: Comparable>: FirestoreQueryFilter {
public var fieldPath: String
public var minValue: Value
private var maxValue: Value
public init(fieldPath: String, minValue: Value, maxValue: Value) {
self.fieldPath = fieldPath
self.minValue = minValue
self.maxValue = maxValue
}
public func build(from: Query) -> Query {
guard maxValue > minValue else {
return from
}
return
from
.whereField(fieldPath, isGreaterThan: minValue)
.whereField(fieldPath, isLessThan: maxValue)
}
public func build<Model>(type: Model.Type) -> Query where Model: FirestoreModel {
let from = Firestore.firestore().collection(type.collectionName)
guard maxValue > minValue else {
return from
}
return
from
.whereField(fieldPath, isGreaterThan: minValue)
.whereField(fieldPath, isLessThan: maxValue)
}
}
public struct FirestoreInFilter: FirestoreQueryFilter {
public var fieldPath: String
public var values: [Any]
public init(fieldPath: String, values: [Any]) {
self.fieldPath = fieldPath
self.values = values
}
public func build(from: Query) -> Query {
from.whereField(fieldPath, in: values)
}
public func build<Model>(type: Model.Type) -> Query where Model : FirestoreModel {
let from = Firestore.firestore().collection(type.collectionName)
return from.whereField(fieldPath, in: values)
}
}
public struct FirestoreEqualFilter: FirestoreQueryFilter {
public var fieldPath: String
public var value: Any?
public init(fieldPath: String, value: Any?) {
self.fieldPath = fieldPath
self.value = value
}
public func build(from: Query) -> Query {
return from.whereField(fieldPath, isEqualTo: value as Any)
}
public func build<Model>(type: Model.Type) -> Query where Model: FirestoreModel {
let from = Firestore.firestore().collection(type.collectionName)
return from.whereField(fieldPath, isEqualTo: value as Any)
}
}
public struct FirestoreContainFilter: FirestoreQueryFilter {
public var fieldPath: String
public var value: Any
public init(fieldPath: String, value: Any) {
self.fieldPath = fieldPath
self.value = value
}
public func build(from: Query) -> Query {
return from.whereField(fieldPath, arrayContains: value)
}
public func build<Model>(type: Model.Type) -> Query where Model: FirestoreModel {
let from = Firestore.firestore().collection(type.collectionName)
return build(from: from)
}
}
public enum EasyFirebaseFirestoreError: Error {
// Decode/Encode
case failedToDecode(data: [String: Any]?)
// Ref
case alreadyExists(ref: DocumentReference)
case notFound(ref: DocumentReference)
// Timestamp
case invalidTimestamp(createdAt: Timestamp?, updatedAt: Timestamp?)
case refNotExists
}
// MARK: - Document Change Types
/// Represents the type of change that occurred on a document.
public enum FirestoreDocumentChangeType: Sendable {
/// A document was added to the result set.
case added
/// A document was modified in the result set.
case modified
/// A document was removed from the result set.
case removed
}
/// Represents a change to a document in a Firestore collection.
public struct FirestoreDocumentChange<Model: FirestoreModel> {
/// The type of change (added, modified, or removed).
public let type: FirestoreDocumentChangeType
/// The document that was changed.
public let document: Model
/// The index of the document in the old snapshot (before the change).
/// For `.added` documents, this is `nil`.
public let oldIndex: Int?
/// The index of the document in the new snapshot (after the change).
/// For `.removed` documents, this is `nil`.
public let newIndex: Int?
public init(
type: FirestoreDocumentChangeType,
document: Model,
oldIndex: Int?,
newIndex: Int?
) {
self.type = type
self.document = document
self.oldIndex = oldIndex
self.newIndex = newIndex
}
}
public actor FirestoreClient {
public let firestore = Firestore.firestore()
public private(set) var documentListeners: [DocumentReference: ListenerRegistration] = [:]
public private(set) var queryListeners: [Query: ListenerRegistration] = [:]
public init() {}
}
// MARK: - FirestoreModel
extension FirestoreClient {
// MARK: Write
public func writeTransaction<Model: FirestoreModel, FieldValue>(
_ model: Model,
fieldPath: WritableKeyPath<Model, FieldValue>,
fieldValue: FieldValue,
beforeCommit: @escaping ((old: FieldValue, new: FieldValue)) -> FieldValue
) async throws {
var model = model
guard let ref = model.ref else {
throw EasyFirebaseFirestoreError.refNotExists
}
_ = try await firestore.runTransaction { transaction, errorPointeer in
do {
let snapshot = try transaction.getDocument(ref)
let data = try snapshot.data(as: Model.self)
let currentFieldValue = data[keyPath: fieldPath]
let newFieldValue = beforeCommit((currentFieldValue, fieldValue))
model[keyPath: fieldPath] = newFieldValue
try transaction.setData(from: model, forDocument: ref)
} catch {
errorPointeer?.pointee = error as NSError
}
return
}
}
/// Update document's data or Create new document if `model.ref` is nil.
@discardableResult
public func write<Model: FirestoreModel>(
_ model: Model,
newDocumentIdIfNotExists: String? = nil
) async throws -> DocumentReference {
let ref: DocumentReference
if let existingRef = model.ref {
ref = existingRef
} else {
ref = Model.generateDocumentReference(firestore: firestore, id: newDocumentIdIfNotExists)
}
return try await withCheckedThrowingContinuation { continuation in
do {
try ref.setData(from: model, merge: true) { error in
if let error {
continuation.resume(throwing: error)
return
}
continuation.resume(returning: ref)
}
} catch {
continuation.resume(throwing: error)
}
}
}
// MARK: Get
public func get<Model: FirestoreModel>(
documentId: String,
includeCache: Bool = true
) async throws -> Model {
let ref = Model.generateDocumentReference(firestore: firestore, id: documentId)
let snapshot = try await ref.getDocument(source: includeCache ? .default : .server)
guard snapshot.exists else {
throw EasyFirebaseFirestoreError.notFound(ref: ref)
}
return try FirestoreClient.putSnaphotTogether(snapshot)
}
public func get<Model: FirestoreModel>(
filter: [FirestoreQueryFilter] = [],
includeCache: Bool = true,
order: [FirestoreQueryOrder] = [],
limit: Int? = nil
) async throws -> [Model] {
let query = createQuery(modelType: Model.self, filter: filter)
.build(order: order, limit: limit)
let snapshot = try await query.getDocuments(source: includeCache ? .default : .server)
return try FirestoreClient.putSnaphotsTogether(snapshot)
}
// MARK: Listen
public func listen<Model: FirestoreModel>(
documentId: String,
includeCache: Bool = true
) -> AsyncThrowingStream<Model, Error> {
let ref = Model.generateDocumentReference(firestore: firestore, id: documentId)
documentListeners[ref]?.remove()
return AsyncThrowingStream { [weak self] continuation in
let listener = ref.addSnapshotListener(
includeMetadataChanges: includeCache
) { snapshot, error in
if let error = error {
continuation.yield(with: .failure(error))
return
}
guard let snapshot = snapshot else {
return
}
let isCache = snapshot.metadata.isFromCache
if isCache, !includeCache {
return
}
do {
let model = try snapshot.data(as: Model.self)
continuation.yield(model)
} catch {
continuation.yield(with: .failure(error))
}
}
continuation.onTermination = { _ in
listener.remove()
}
Task {
await self?.documentListeners[ref]?.remove()
await self?.setListener(key: ref, value: listener)
}
}
}
public func listen<Model: FirestoreModel>(
filter: [FirestoreQueryFilter] = [],
includeCache: Bool = true,
order: [FirestoreQueryOrder] = [],
limit: Int? = nil
) -> AsyncThrowingStream<[Model], Error> {
let query = createQuery(modelType: Model.self, filter: filter)
.build(
order: order,
limit: limit
)
queryListeners[query]?.remove()
return AsyncThrowingStream { [weak self] continuation in
let listener = query.addSnapshotListener { (snapshots, error) in
if let error = error {
continuation.yield(with: .failure(error))
return
}
guard let snapshots = snapshots else {
return
}
if !includeCache, snapshots.metadata.isFromCache {
// Ignore this event if `includeCache` is `false` and the source is from cache.
return
}
do {
let models: [Model] = try FirestoreClient.putSnaphotsTogether(snapshots)
continuation.yield(models)
} catch {
continuation.yield(with: .failure(error))
}
}
continuation.onTermination = { _ in
listener.remove()
}
Task {
await self?.queryListeners[query]?.remove()
await self?.setListener(key: query, value: listener)
}
}
}
/// Listens to document changes in a collection, returning only differential updates.
/// - Parameters:
/// - filter: Optional array of query filters
/// - includeCache: Whether to include cache updates (defaults to true)
/// - order: Optional array of ordering criteria
/// - limit: Optional limit on number of documents
/// - Returns: AsyncThrowingStream of document change arrays
public func listenChanges<Model: FirestoreModel>(
filter: [FirestoreQueryFilter] = [],
includeCache: Bool = true,
order: [FirestoreQueryOrder] = [],
limit: Int? = nil
) -> AsyncThrowingStream<[FirestoreDocumentChange<Model>], Error> {
let query = createQuery(modelType: Model.self, filter: filter)
.build(
order: order,
limit: limit
)
queryListeners[query]?.remove()
return AsyncThrowingStream { [weak self] continuation in
let listener = query.addSnapshotListener { (snapshots, error) in
if let error = error {
continuation.yield(with: .failure(error))
return
}
guard let snapshots = snapshots else {
return
}
if !includeCache, snapshots.metadata.isFromCache {
// Ignore this event if `includeCache` is `false` and the source is from cache.
return
}
do {
let changes: [FirestoreDocumentChange<Model>] =
try FirestoreClient.mapDocumentChanges(snapshots.documentChanges)
continuation.yield(changes)
} catch {
continuation.yield(with: .failure(error))
}
}
continuation.onTermination = { _ in
listener.remove()
}
Task {
await self?.queryListeners[query]?.remove()
await self?.setListener(key: query, value: listener)
}
}
}
// MARK: Delete
public func delete<Model: FirestoreModel>(_ model: Model) async throws {
guard let ref = model.ref else {
throw EasyFirebaseFirestoreError.refNotExists
}
try await ref.delete()
}
private func createQuery<Model: FirestoreModel>(
modelType: Model.Type,
filter: [FirestoreQueryFilter]
) -> Query {
var query: Query = firestore.collection(modelType.collectionName)
for element in filter {
query = element.build(from: query)
}
return query
}
// MARK: Stop Listener
public func stopListening<Model: FirestoreModel>(type: Model.Type) {
let query = firestore.collection(type.collectionName)
queryListeners[query]?.remove()
}
/// Not applicable to SubCollectionModel
public func stopListening<Model: FirestoreModel>(type: Model.Type, documentID: String) {
let ref = firestore.collection(type.collectionName).document(documentID)
stopListening(ref: ref)
}
public func stopListening(ref: DocumentReference) {
documentListeners[ref]?.remove()
}
/// If you want to stop listening to SubCollectionModel, please use this method
public func stopListeningAll() {
documentListeners.forEach({ $0.value.remove() })
queryListeners.forEach({ $0.value.remove() })
}
// MARK: Internal
internal func setListener(
key ref: DocumentReference, value documentListener: ListenerRegistration
) {
documentListeners[ref] = documentListener
}
internal func setListener(key query: Query, value documentListener: ListenerRegistration) {
queryListeners[query] = documentListener
}
}
// MARK: - SubCollectionModel
extension FirestoreClient {
public func create<Model: SubCollectionModel>(_ model: Model) async throws {
guard let ref = model.ref else {
throw EasyFirebaseFirestoreError.refNotExists
}
if model.updatedAt != nil || model.createdAt != nil {
throw EasyFirebaseFirestoreError.invalidTimestamp(
createdAt: model.createdAt,
updatedAt: model.updatedAt
)
}
return try await withCheckedThrowingContinuation { continuation in
do {
try ref.setData(from: model, merge: false) { (error) in
if let error = error {
continuation.resume(throwing: error)
return
}
continuation.resume(returning: ())
}
} catch {
continuation.resume(throwing: error)
}
}
}
public func update<Model: FirestoreModel & SubCollectionModel>(_ model: Model) async throws {
guard let ref = model.ref else {
throw EasyFirebaseFirestoreError.refNotExists
}
if model.updatedAt == nil || model.createdAt == nil {
throw EasyFirebaseFirestoreError.invalidTimestamp(
createdAt: model.createdAt,
updatedAt: model.updatedAt
)
}
return try await withCheckedThrowingContinuation { continuation in
do {
try ref.setData(from: model, merge: false) { (error) in
if let error = error {
continuation.resume(throwing: error)
return
}
continuation.resume(returning: ())
}
} catch {
continuation.resume(throwing: error)
}
}
}
public func get<Model: SubCollectionModel>(
parent parentDocumentId: String,
filter: [FirestoreQueryFilter] = [],
includeCache: Bool = true,
order: [FirestoreQueryOrder] = [],
limit: Int? = nil
) async throws -> [Model] {
let snapshot = try await createQueryOfSubCollection(
parent: parentDocumentId,
modelType: Model.self,
filter: filter,
order: order,
limit: limit
)
.getDocuments()
return try FirestoreClient.putSnaphotsTogether(snapshot)
}
public func get<Model: SubCollectionModel>(
documentId: String,
parent parentUid: String,
includeCache: Bool = true
) async throws -> Model {
let collectionName = Model.parentCollectionName
let ref: DocumentReference = firestore.collection(collectionName)
.document(parentUid)
.collection(Model.collectionName)
.document(documentId)
let snapshot = try await ref.getDocument()
return try FirestoreClient.putSnaphotTogether(snapshot)
}
public func listen<Model: FirestoreModel & SubCollectionModel>(
parentDocumentId parentUID: String,
documentId: String,
filter: [FirestoreQueryFilter],
includeCache: Bool = true,
order: [FirestoreQueryOrder],
limit: Int?
) -> AsyncThrowingStream<Model, Error> {
let ref = firestore.collection(Model.parentCollectionName).document(parentUID)
.collection(Model.collectionName).document(documentId)
return AsyncThrowingStream { [weak self] continuation in
let listener = ref.addSnapshotListener(
includeMetadataChanges: includeCache
) { snapshot, error in
if let error = error {
continuation.yield(with: .failure(error))
return
}
guard let snapshot = snapshot else {
return
}
let isCache = snapshot.metadata.isFromCache
if isCache, !includeCache {
return
}
do {
let model = try snapshot.data(as: Model.self)
continuation.yield(model)
} catch {
continuation.yield(with: .failure(error))
}
}
continuation.onTermination = { _ in
listener.remove()
}
Task {
await self?.documentListeners[ref]?.remove()
await self?.setListener(key: ref, value: listener)
}
}
}
public func listen<Model: FirestoreModel & SubCollectionModel>(
parent parentUid: String,
superParent superParentUid: String?,
filter: [FirestoreQueryFilter],
includeCache: Bool = true,
order: [FirestoreQueryOrder],
limit: Int?
) -> AsyncThrowingStream<[Model], any Error> {
let query = createQueryOfSubCollection(
parent: parentUid,
modelType: Model.self,
filter: filter,
order: order,
limit: limit
)
return AsyncThrowingStream { [weak self] continuation in
let listener = query.addSnapshotListener { (snapshots, error) in
if let error = error {
continuation.yield(with: .failure(error))
return
}
guard let snapshots = snapshots else {
return
}
if !includeCache, snapshots.metadata.isFromCache {
// Ignore this event if `includeCache` is `false` and the source is from cache.
return
}
do {
let models: [Model] = try FirestoreClient.putSnaphotsTogether(snapshots)
continuation.yield(models)
} catch {
continuation.yield(with: .failure(error))
}
}
continuation.onTermination = { _ in
listener.remove()
}
Task {
await self?.queryListeners[query]?.remove()
await self?.setListener(key: query, value: listener)
}
}
}
/// Listens to document changes in a subcollection, returning only differential updates.
/// - Parameters:
/// - parentUid: The parent document ID
/// - superParentUid: Optional super parent document ID (for nested subcollections)
/// - filter: Array of query filters
/// - includeCache: Whether to include cache updates
/// - order: Array of ordering criteria
/// - limit: Optional limit on number of documents
/// - Returns: AsyncThrowingStream of document change arrays
public func listenChanges<Model: FirestoreModel & SubCollectionModel>(
parent parentUid: String,
superParent superParentUid: String?,
filter: [FirestoreQueryFilter],
includeCache: Bool = true,
order: [FirestoreQueryOrder],
limit: Int?
) -> AsyncThrowingStream<[FirestoreDocumentChange<Model>], any Error> {
let query = createQueryOfSubCollection(
parent: parentUid,
modelType: Model.self,
filter: filter,
order: order,
limit: limit
)
return AsyncThrowingStream { [weak self] continuation in
let listener = query.addSnapshotListener { (snapshots, error) in
if let error = error {
continuation.yield(with: .failure(error))
return
}
guard let snapshots = snapshots else {
return
}
if !includeCache, snapshots.metadata.isFromCache {
// Ignore this event if `includeCache` is `false` and the source is from cache.
return
}
do {
let changes: [FirestoreDocumentChange<Model>] =
try FirestoreClient.mapDocumentChanges(snapshots.documentChanges)
continuation.yield(changes)
} catch {
continuation.yield(with: .failure(error))
}
}
continuation.onTermination = { _ in
listener.remove()
}
Task {
await self?.queryListeners[query]?.remove()
await self?.setListener(key: query, value: listener)
}
}
}
private func createQueryOfSubCollection<Model: FirestoreModel & SubCollectionModel>(
parent parentUid: String,
modelType: Model.Type,
filter: [FirestoreQueryFilter],
order: [FirestoreQueryOrder],
limit: Int?
) -> Query {
var query: Query =
firestore
.collection(modelType.parentCollectionName)
.document(parentUid)
.collection(modelType.collectionName)
for element in filter {
query = element.build(from: query).build(order: order, limit: limit)
}
return query
}
}
// MARK: - CollectionGroup
extension FirestoreClient {
public func getCollectionGroup<Model: FirestoreModel>(
filter: [FirestoreQueryFilter] = [],
includeCache: Bool = true,
order: [FirestoreQueryOrder] = [],
limit: Int? = nil
) async throws -> [Model] {
let collectionName = Model.collectionName
let snapshots = try await createQuery(
from: firestore.collectionGroup(collectionName),
filter: filter
)
.build(order: order, limit: limit)
.getDocuments(source: includeCache ? .default : .server)
let models: [Model] = try FirestoreClient.putSnaphotsTogether(snapshots)
return models
}
public func listenCollectionGroup<Model: FirestoreModel>(
collectionName: String,
filter: [FirestoreQueryFilter] = [],
includeCache: Bool = true,
order: [FirestoreQueryOrder] = [],
limit: Int? = nil
) -> AsyncThrowingStream<[Model], Error> {
let query = createQuery(
from: firestore.collectionGroup(collectionName),
filter: filter
).build(order: order, limit: limit)
return AsyncThrowingStream { [weak self] continuation in
let listener = query.addSnapshotListener { (snapshots, error) in
if let error = error {
continuation.yield(with: .failure(error))
return
}
guard let snapshots = snapshots else {
return
}
if !includeCache, snapshots.metadata.isFromCache {
// Ignore this event if `includeCache` is `false` and the source is from cache.
return
}
do {
let models: [Model] = try FirestoreClient.putSnaphotsTogether(snapshots)
continuation.yield(models)
} catch {
continuation.yield(with: .failure(error))
}
}
continuation.onTermination = { _ in
listener.remove()
}
Task {
await self?.queryListeners[query]?.remove()
await self?.setListener(key: query, value: listener)
}
}
}
/// Listens to document changes in a collection group, returning only differential updates.
/// - Parameters:
/// - collectionName: The collection name for the group
/// - filter: Optional array of query filters
/// - includeCache: Whether to include cache updates
/// - order: Optional array of ordering criteria
/// - limit: Optional limit on number of documents
/// - Returns: AsyncThrowingStream of document change arrays
public func listenCollectionGroupChanges<Model: FirestoreModel>(
collectionName: String,
filter: [FirestoreQueryFilter] = [],
includeCache: Bool = true,
order: [FirestoreQueryOrder] = [],
limit: Int? = nil
) -> AsyncThrowingStream<[FirestoreDocumentChange<Model>], Error> {
let query = createQuery(
from: firestore.collectionGroup(collectionName),
filter: filter
).build(order: order, limit: limit)
return AsyncThrowingStream { [weak self] continuation in
let listener = query.addSnapshotListener { (snapshots, error) in
if let error = error {
continuation.yield(with: .failure(error))
return
}
guard let snapshots = snapshots else {
return
}
if !includeCache, snapshots.metadata.isFromCache {
// Ignore this event if `includeCache` is `false` and the source is from cache.
return
}
do {
let changes: [FirestoreDocumentChange<Model>] =
try FirestoreClient.mapDocumentChanges(snapshots.documentChanges)
continuation.yield(changes)
} catch {
continuation.yield(with: .failure(error))
}
}
continuation.onTermination = { _ in
listener.remove()
}
Task {
await self?.queryListeners[query]?.remove()
await self?.setListener(key: query, value: listener)
}
}
}
private func createQuery(from ref: Query, filter: [FirestoreQueryFilter]) -> Query {
var query: Query = ref
for element in filter {
query = element.build(from: query)
}
return query
}
}
// MARK: Order
extension Query {
func build(order: [FirestoreQueryOrder], limit: Int?) -> Query {
var ref = self
order.forEach({ order in
ref = order.build(from: ref)
})
if let limit = limit {
return ref.limit(to: limit)
}
return ref
}
}
// MARK: - Internal common methods
extension FirestoreClient {
static func putSnaphotsTogether<Model: FirestoreModel>(_ snapshots: QuerySnapshot) throws
-> [Model]
{
let documents = snapshots.documents
let models = try documents.map { document -> Model in
let model = try document.data(as: Model.self)
return model
}
return models
}
static func putSnaphotTogether<Model: FirestoreModel>(_ snapshot: DocumentSnapshot) throws
-> Model
{
let model = try snapshot.data(as: Model.self)
return model
}
/// Converts Firebase DocumentChange objects to FirestoreDocumentChange objects.
static func mapDocumentChanges<Model: FirestoreModel>(
_ changes: [DocumentChange]
) throws -> [FirestoreDocumentChange<Model>] {
try changes.map { change -> FirestoreDocumentChange<Model> in
let model = try change.document.data(as: Model.self)
let changeType: FirestoreDocumentChangeType
switch change.type {
case .added:
changeType = .added
case .modified:
changeType = .modified
case .removed:
changeType = .removed
}
// Firebase uses UInt for indices
// oldIndex is NSNotFound for added documents
// newIndex is NSNotFound for removed documents
let oldIndex: Int? = change.oldIndex == NSNotFound ? nil : Int(change.oldIndex)
let newIndex: Int? = change.newIndex == NSNotFound ? nil : Int(change.newIndex)
return FirestoreDocumentChange(
type: changeType,
document: model,
oldIndex: oldIndex,
newIndex: newIndex
)
}
}
}