-
-
Notifications
You must be signed in to change notification settings - Fork 4
/
listenable_firestore_model_adapter.dart
976 lines (924 loc) · 30.6 KB
/
listenable_firestore_model_adapter.dart
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
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
part of '/katana_model_firestore.dart';
/// Model adapter with Firebase Firestore available.
///
/// It monitors all documents in Firestore for changes and notifies you of any changes on the remote side.
///
/// Firestore application settings must be completed in advance and [FirebaseCore.initialize] must be executed.
///
/// Basically, the default [FirebaseFirestore.instance] is used, but it is possible to use a specified database by passing [database] when creating the adapter.
///
/// You can initialize Firebase by passing [options].
///
/// The internal database can be specified in [localDatabase].
///
/// By passing data to [initialValue], the database can be used as a data mockup because it contains data in advance.
///
/// By adding [prefix], all paths can be prefixed, enabling operations such as separating data storage locations for each Flavor.
///
/// FirebaseFirestoreを利用できるようにしたモデルアダプター。
///
/// Firestoreのすべてのドキュメントの変更を監視し、リモート側で変更があればそれを通知します。
///
/// 事前にFirestoreのアプリ設定を済ませておくことと[FirebaseCore.initialize]を実行しておきます。
///
/// 基本的にデフォルトの[FirebaseFirestore.instance]が利用されますが、アダプターの作成時に[database]を渡すことで指定されたデータベースを利用することが可能です。
///
/// [options]を渡すことでFirebaseの初期化を行うことができます。
///
/// 内部データベースは[localDatabase]で指定することができます。
///
/// [initialValue]にデータを渡すことで予めデータが入った状態でデータベースを利用することができるためデータモックとして利用することができます。
///
/// [prefix]を追加することですべてのパスにプレフィックスを付与することができ、Flavorごとにデータの保存場所を分けるなどの運用が可能です。
class ListenableFirestoreModelAdapter extends ModelAdapter
implements FirestoreModelAdapterBase {
/// Model adapter with Firebase Firestore available.
///
/// It monitors all documents in Firestore for changes and notifies you of any changes on the remote side.
///
/// Firestore application settings must be completed in advance and [FirebaseCore.initialize] must be executed.
///
/// Basically, the default [FirebaseFirestore.instance] is used, but it is possible to use a specified database by passing [database] when creating the adapter.
///
/// You can initialize Firebase by passing [options].
///
/// The internal database can be specified in [localDatabase].
///
/// By passing data to [initialValue], the database can be used as a data mockup because it contains data in advance.
///
/// By adding [prefix], all paths can be prefixed, enabling operations such as separating data storage locations for each Flavor.
///
/// FirebaseFirestoreを利用できるようにしたモデルアダプター。
///
/// Firestoreのすべてのドキュメントの変更を監視し、リモート側で変更があればそれを通知します。
///
/// 事前にFirestoreのアプリ設定を済ませておくことと[FirebaseCore.initialize]を実行しておきます。
///
/// 基本的にデフォルトの[FirebaseFirestore.instance]が利用されますが、アダプターの作成時に[database]を渡すことで指定されたデータベースを利用することが可能です。
///
/// [options]を渡すことでFirebaseの初期化を行うことができます。
///
/// 内部データベースは[localDatabase]で指定することができます。
///
/// [initialValue]にデータを渡すことで予めデータが入った状態でデータベースを利用することができるためデータモックとして利用することができます。
///
/// [prefix]を追加することですべてのパスにプレフィックスを付与することができ、Flavorごとにデータの保存場所を分けるなどの運用が可能です。
const ListenableFirestoreModelAdapter({
this.initialValue,
FirebaseFirestore? database,
NoSqlDatabase? localDatabase,
FirebaseOptions? options,
this.iosOptions,
this.androidOptions,
this.webOptions,
this.linuxOptions,
this.windowsOptions,
this.macosOptions,
this.prefix,
}) : _options = options,
_database = database,
_localDatabase = localDatabase;
/// The Firestore database instance used in the adapter.
///
/// アダプター内で利用しているFirestoreのデータベースインスタンス。
@override
FirebaseFirestore get database => _database ?? FirebaseFirestore.instance;
final FirebaseFirestore? _database;
/// Caches data retrieved from the specified internal database, Firestore.
///
/// 指定の内部データベース。Firestoreから取得したデータをキャッシュします。
NoSqlDatabase get localDatabase {
final database = _localDatabase ?? sharedLocalDatabase;
if (initialValue.isNotEmpty && !database.isInitialValueRegistered) {
for (final raw in initialValue!) {
if (raw is ModelInitialDocument) {
final map = raw.toMap(raw.value);
database.setInitialValue(
_path(raw.path),
raw.filterOnSave(map, raw.value),
);
} else if (raw is ModelInitialCollection) {
for (final tmp in raw.value.entries) {
final map = raw.toMap(tmp.value);
database.setInitialValue(
_path("${raw.path}/${tmp.key}"),
raw.filterOnSave(map, tmp.value),
);
}
}
}
}
return database;
}
final NoSqlDatabase? _localDatabase;
/// A common internal database throughout the app.
///
/// アプリ内全体での共通の内部データベース。
static final NoSqlDatabase sharedLocalDatabase = NoSqlDatabase();
/// Actual data when used as a mock-up.
///
/// モックアップとして利用する際の実データ。
final List<ModelInitialValue>? initialValue;
/// A special class can be registered as a [ModelFieldValue] by passing [FirestoreModelFieldValueConverter] to [converter].
///
/// [FirestoreModelFieldValueConverter]を[converter]に渡すことで特殊なクラスを[ModelFieldValue]として登録することができます。
static void registerConverter(FirestoreModelFieldValueConverter converter) {
_converters.add(converter);
}
/// By passing [FirestoreModelFieldValueConverter] to [converter], you can release an already registered [FirestoreModelFieldValueConverter].
///
/// [converter]に[FirestoreModelFieldValueConverter]を渡すことですでに登録されている[FirestoreModelFieldValueConverter]を解除することができます。
static void unregisterConverter(FirestoreModelFieldValueConverter converter) {
_converters.remove(converter);
}
static final Set<FirestoreModelFieldValueConverter> _converters = {
...FirestoreModelFieldValueConverter.defaultConverters
};
/// Options for initializing Firebase.
///
/// If platform-specific options are specified, they take precedence.
///
/// Firebaseを初期化する際のオプション。
///
/// プラットフォーム固有のオプションが指定されている場合はそちらが優先されます。
FirebaseOptions? get options {
if (UniversalPlatform.isIOS) {
return iosOptions ?? _options;
} else if (UniversalPlatform.isAndroid) {
return androidOptions ?? _options;
} else if (UniversalPlatform.isWeb) {
return webOptions ?? _options;
} else if (UniversalPlatform.isLinux) {
return linuxOptions ?? _options;
} else if (UniversalPlatform.isWindows) {
return windowsOptions ?? _options;
} else if (UniversalPlatform.isMacOS) {
return macosOptions ?? _options;
} else {
return _options;
}
}
/// Options for initializing Firebase.
///
/// If options for other platforms are specified, these are ignored.
///
/// Firebaseを初期化する際のオプション。
///
/// 他のプラットフォーム用のオプションが指定されている場合はこちらは無視されます。
final FirebaseOptions? _options;
/// Options for initializing Firebase.
///
/// Applies to IOS only.
///
/// If [options] is specified, this takes precedence.
///
/// Firebaseを初期化する際のオプション。
///
/// IOSのみに適用されます。
///
/// [options]が指定されている場合はこちらが優先されます。
final FirebaseOptions? iosOptions;
/// Options for initializing Firebase.
///
/// Applies to Android only.
///
/// If [options] is specified, this takes precedence.
///
/// Firebaseを初期化する際のオプション。
///
/// Androidのみに適用されます。
///
/// [options]が指定されている場合はこちらが優先されます。
final FirebaseOptions? androidOptions;
/// Options for initializing Firebase.
///
/// Applies to Web only.
///
/// If [options] is specified, this takes precedence.
///
/// Firebaseを初期化する際のオプション。
///
/// Webのみに適用されます。
///
/// [options]が指定されている場合はこちらが優先されます。
final FirebaseOptions? webOptions;
/// Options for initializing Firebase.
///
/// Applies to Web only.
///
/// If [options] is specified, this takes precedence.
///
/// Firebaseを初期化する際のオプション。
///
/// Webのみに適用されます。
///
/// [options]が指定されている場合はこちらが優先されます。
final FirebaseOptions? windowsOptions;
/// Options for initializing Firebase.
///
/// Applies to MacOS only.
///
/// If [options] is specified, this takes precedence.
///
/// Firebaseを初期化する際のオプション。
///
/// MacOSのみに適用されます。
///
/// [options]が指定されている場合はこちらが優先されます。
final FirebaseOptions? macosOptions;
/// Options for initializing Firebase.
///
/// Applies to Linux only.
///
/// If [options] is specified, this takes precedence.
///
/// Firebaseを初期化する際のオプション。
///
/// Linuxのみに適用されます。
///
/// [options]が指定されている場合はこちらが優先されます。
final FirebaseOptions? linuxOptions;
/// Path prefix.
///
/// パスのプレフィックス。
@override
final String? prefix;
@override
Future<void> deleteDocument(ModelAdapterDocumentQuery query) async {
_assert();
await FirebaseCore.initialize(options: options);
await _documentReference(query).delete();
_FirestoreCache.getCache(options).set(_path(query.query.path));
}
@override
Future<DynamicMap> loadDocument(ModelAdapterDocumentQuery query) async {
_assert();
await FirebaseCore.initialize(options: options);
final snapshot = await _documentReference(query).get();
var res = _convertFrom(snapshot.data()?.cast() ?? {});
if (res.isEmpty) {
final localRes =
await localDatabase.getInitialDocument(query, prefix: prefix);
if (localRes.isNotEmpty) {
res = localRes!;
}
}
_FirestoreCache.getCache(options).set(_path(query.query.path), res);
return res;
}
@override
void disposeCollection(ModelAdapterCollectionQuery query) {
_assert();
}
@override
void disposeDocument(ModelAdapterDocumentQuery query) {
_assert();
}
@override
Future<Map<String, DynamicMap>> loadCollection(
ModelAdapterCollectionQuery query,
) async {
_assert();
await FirebaseCore.initialize(options: options);
final snapshot = await Future.wait<QuerySnapshot<DynamicMap>>(
_collectionReference(query).map((reference) => reference.get()),
);
final res = snapshot.expand((e) => e.docChanges).toMap(
(e) => MapEntry(e.doc.id, _convertFrom(e.doc.data()?.cast() ?? {})),
);
final localRes =
await localDatabase.getInitialCollection(query, prefix: prefix);
if (localRes.isNotEmpty) {
for (final entry in localRes!.entries) {
if (res.containsKey(entry.key)) {
continue;
}
if (!query.query.hasMatchAsMap(entry.value)) {
continue;
}
res[entry.key] = entry.value;
}
}
for (final doc in res.entries) {
_FirestoreCache.getCache(options).set(
"${_path(query.query.path)}/${doc.key}",
doc.value,
);
}
return res;
}
@override
Future<num> loadAggregation(
ModelAdapterCollectionQuery query,
ModelAggregateQuery aggregateQuery,
) async {
_assert();
await FirebaseCore.initialize(options: options);
switch (aggregateQuery.type) {
case ModelAggregateQueryType.count:
final snapshot = await Future.wait<AggregateQuerySnapshot>(
_collectionReference(
query.copyWith(
query: query.query.remove(ModelQueryFilterType.limit),
),
).map(
(reference) => reference.count().get(),
),
);
final res = snapshot.fold<int>(0, (p, e) => p + (e.count ?? 0));
return res;
case ModelAggregateQueryType.sum:
final key = aggregateQuery.key;
assert(
key.isNotEmpty,
"Enter [key] for [ModelAggregateQueryType.sum].",
);
final snapshot = await Future.wait<AggregateQuerySnapshot>(
_collectionReference(
query.copyWith(
query: query.query.remove(ModelQueryFilterType.limit),
),
).map(
(reference) => reference.aggregate(sum(key!)).get(),
),
);
final res = snapshot.fold<double>(0.0, (p, e) => p + (e.count ?? 0.0));
return res;
case ModelAggregateQueryType.average:
final key = aggregateQuery.key;
assert(
aggregateQuery.key.isNotEmpty,
"Enter [key] for [ModelAggregateQueryType.average].",
);
final snapshot = await Future.wait<AggregateQuerySnapshot>(
_collectionReference(
query.copyWith(
query: query.query.remove(ModelQueryFilterType.limit),
),
).map(
(reference) => reference.aggregate(average(key!)).get(),
),
);
if (snapshot.isEmpty) {
return 0.0;
}
final res = snapshot.fold<double>(0.0, (p, e) => p + (e.count ?? 0.0)) /
snapshot.length;
return res;
}
}
@override
Future<void> saveDocument(
ModelAdapterDocumentQuery query,
DynamicMap value,
) async {
_assert();
await FirebaseCore.initialize(options: options);
final converted = _convertTo(
value,
_FirestoreCache.getCache(options).get(_path(query.query.path)) ?? {},
);
await _documentReference(query).set(
converted,
SetOptions(merge: true),
);
_FirestoreCache.getCache(options).set(
_path(query.query.path),
value,
);
}
@override
bool get availableListen => true;
@override
Future<List<StreamSubscription>> listenCollection(
ModelAdapterCollectionQuery query,
) async {
_assert();
await FirebaseCore.initialize(options: options);
final localRes =
await localDatabase.getInitialCollection(query, prefix: prefix);
if (localRes.isNotEmpty) {
for (final entry in localRes!.entries) {
if (!query.query.hasMatchAsMap(entry.value)) {
continue;
}
query.callback?.call(
ModelUpdateNotification(
path: entry.key,
id: entry.key.last(),
status: ModelUpdateNotificationStatus.added,
value: entry.value,
newIndex: 0,
origin: query.origin,
listen: availableListen,
query: query.query,
),
);
}
}
final streams =
_collectionReference(query).map((reference) => reference.snapshots());
final subscriptions = streams.map((e) {
return e.listen((event) {
for (final doc in event.docChanges) {
final path = doc.doc.reference.path;
final converted = _convertFrom(doc.doc.data()?.cast() ?? {});
query.callback?.call(
ModelUpdateNotification(
path: path,
id: doc.doc.id,
status: _status(doc.type),
value: converted,
oldIndex: doc.oldIndex,
newIndex: doc.newIndex,
origin: query.origin,
listen: availableListen,
query: query.query,
),
);
_FirestoreCache.getCache(options).set(
_path(query.query.path),
converted,
);
}
});
}).toList();
await Future.wait(streams.map((stream) => stream.first));
return subscriptions;
}
@override
Future<List<StreamSubscription>> listenDocument(
ModelAdapterDocumentQuery query,
) async {
_assert();
await FirebaseCore.initialize(options: options);
final localRes =
await localDatabase.getInitialDocument(query, prefix: prefix);
if (localRes.isNotEmpty) {
query.callback?.call(
ModelUpdateNotification(
path: query.query.path.parentPath(),
id: query.query.path.last(),
status: ModelUpdateNotificationStatus.modified,
value: localRes!,
origin: query.origin,
listen: availableListen,
query: query.query,
),
);
}
final stream = _documentReference(query).snapshots();
// ignore: cancel_subscriptions
final subscription = stream.listen((doc) {
final converted = _convertFrom(doc.data()?.cast() ?? {});
if (converted.isEmpty && localRes.isNotEmpty) {
return;
}
query.callback?.call(
ModelUpdateNotification(
path: doc.reference.path,
id: doc.id,
status: ModelUpdateNotificationStatus.modified,
value: converted,
origin: query.origin,
listen: availableListen,
query: query.query,
),
);
_FirestoreCache.getCache(options).set(
_path(query.query.path),
converted,
);
});
await stream.first;
return [subscription];
}
@override
void deleteOnTransaction(
ModelTransactionRef ref,
ModelAdapterDocumentQuery query,
) {
_assert();
if (ref is! ListenableFirestoreModelTransactionRef) {
throw Exception("[ref] is not [ListenableFirestoreModelTransactionRef].");
}
ref._transaction.delete(database.doc(_path(query.query.path)));
ref._localTransaction.add(() async {
_FirestoreCache.getCache(options).set(_path(query.query.path));
});
}
@override
FutureOr<DynamicMap> loadOnTransaction(
ModelTransactionRef ref,
ModelAdapterDocumentQuery query,
) async {
_assert();
if (ref is! ListenableFirestoreModelTransactionRef) {
throw Exception("[ref] is not [ListenableFirestoreModelTransactionRef].");
}
final snapshot =
await ref._transaction.get(database.doc(_path(query.query.path)));
var res = _convertFrom(snapshot.data() ?? {});
if (res.isEmpty) {
final localRes =
await localDatabase.getInitialDocument(query, prefix: prefix);
if (localRes.isNotEmpty) {
res = localRes!;
}
}
_FirestoreCache.getCache(options).set(_path(query.query.path), res);
return res;
}
@override
void saveOnTransaction(
ModelTransactionRef ref,
ModelAdapterDocumentQuery query,
DynamicMap value,
) {
_assert();
if (ref is! ListenableFirestoreModelTransactionRef) {
throw Exception("[ref] is not [ListenableFirestoreModelTransactionRef].");
}
final converted = _convertTo(
value,
_FirestoreCache.getCache(options).get(_path(query.query.path)) ?? {},
);
ref._transaction.set(
database.doc(_path(query.query.path)),
converted,
SetOptions(merge: true),
);
ref._localTransaction.add(() async {
_FirestoreCache.getCache(options).set(_path(query.query.path), value);
});
}
@override
FutureOr<void> runTransaction(
FutureOr<void> Function(
ModelTransactionRef ref,
) transaction,
) async {
_assert();
await FirebaseCore.initialize(options: options);
await database.runTransaction((handler) async {
final ref = ListenableFirestoreModelTransactionRef._(handler);
await transaction.call(ref);
for (final tr in ref._localTransaction) {
await tr.call();
}
});
}
@override
void deleteOnBatch(ModelBatchRef ref, ModelAdapterDocumentQuery query) {
_assert();
if (ref is! ListenableFirestoreModelBatchRef) {
throw Exception("[ref] is not [ListenableFirestoreModelBatchRef].");
}
ref._localBatch.add(
_ListenableFirestoreModelBatchItem(
path: _path(query.query.path),
actions: () async {
await localDatabase.deleteDocument(query, prefix: prefix);
_FirestoreCache.getCache(options).set(_path(query.query.path));
},
),
);
}
@override
FutureOr<void> runBatch(
FutureOr<void> Function(
ModelBatchRef ref,
) batch,
int splitLength,
) async {
assert(
splitLength > 0 && splitLength <= 500,
"[splitLength] must be greater than 0 and less than or equal to 500 in Firestore.",
);
_assert();
await FirebaseCore.initialize(options: options);
final ref = ListenableFirestoreModelBatchRef._();
await batch.call(ref);
await wait(
ref._localBatch.split(splitLength).expand((b) {
final db = database.batch();
final actions = <Future<void>>[];
for (final item in b) {
if (item.value == null) {
db.delete(database.doc(item.path));
} else {
db.set(
database.doc(item.path),
item.value,
SetOptions(merge: true),
);
if (item.actions != null) {
actions.add(item.actions!());
}
}
}
return [db.commit(), ...actions];
}),
);
}
@override
void saveOnBatch(
ModelBatchRef ref,
ModelAdapterDocumentQuery query,
DynamicMap value,
) {
_assert();
if (ref is! ListenableFirestoreModelBatchRef) {
throw Exception("[ref] is not [ListenableFirestoreModelBatchRef].");
}
final converted = _convertTo(
value,
_FirestoreCache.getCache(options).get(_path(query.query.path)) ?? {},
);
ref._localBatch.add(
_ListenableFirestoreModelBatchItem(
path: _path(query.query.path),
value: converted,
actions: () async {
await localDatabase.saveDocument(query, value, prefix: prefix);
_FirestoreCache.getCache(options).set(_path(query.query.path), value);
},
),
);
}
@override
Future<void> clearAll() {
throw UnimplementedError("This function is not available.");
}
DynamicMap _convertFrom(DynamicMap map) {
final res = <String, dynamic>{};
for (final tmp in map.entries) {
final key = tmp.key;
final val = tmp.value;
DynamicMap? replaced;
for (final converter in _converters) {
replaced = converter.convertFrom(key, val, map, this);
if (replaced != null) {
break;
}
}
if (replaced != null) {
res.addAll(replaced);
} else {
res[key] = val;
}
}
return res;
}
DynamicMap _convertTo(DynamicMap map, DynamicMap original) {
final res = <String, dynamic>{};
for (final tmp in map.entries) {
final key = tmp.key;
final val = tmp.value;
DynamicMap? replaced;
for (final converter in _converters) {
replaced = converter.convertTo(key, val, map, this);
if (replaced != null) {
break;
}
}
if (replaced != null) {
res.addAll(replaced);
} else {
res[key] = val;
}
}
return res;
}
Query<DynamicMap> _query(
Query<DynamicMap> firestoreQuery,
ModelAdapterCollectionQuery query,
) {
final filters = query.query.filters;
for (final filter in filters) {
for (final converter in _converters) {
final res = converter.filterQuery(firestoreQuery, filter, query, this);
if (res != null) {
firestoreQuery = res;
break;
}
}
}
for (final filter in filters) {
for (final converter in _converters) {
final res = converter.orderQuery(firestoreQuery, filter, query, this);
if (res != null) {
firestoreQuery = res;
break;
}
}
}
return firestoreQuery;
}
@override
String _path(String original) {
if (prefix.isEmpty) {
return original;
}
_assert();
final p = prefix!.trimQuery().trimString("/");
final o = original.trimQuery().trimString("/");
return "$p/$o";
}
DocumentReference<DynamicMap> _documentReference(
ModelAdapterDocumentQuery query,
) =>
database.doc(_path(query.query.path));
List<Query<DynamicMap>> _collectionReference(
ModelAdapterCollectionQuery query,
) {
final filters = query.query.filters;
final containsAny = filters
.where((e) => e.type == ModelQueryFilterType.arrayContainsAny)
.toList();
final whereIn =
filters.where((e) => e.type == ModelQueryFilterType.whereIn).toList();
final whereNotIn = filters
.where((e) => e.type == ModelQueryFilterType.whereNotIn)
.toList();
final geoHash =
filters.where((e) => e.type == ModelQueryFilterType.geoHash).toList();
assert(
containsAny.length <= 1,
"Multiple conditions cannot be defined for `containsAny`.",
);
assert(
whereIn.length <= 1,
"Multiple conditions cannot be defined for `where`.",
);
assert(
whereNotIn.length <= 1,
"Multiple conditions cannot be defined for `notWhere`.",
);
assert(
geoHash.length <= 1,
"Multiple conditions cannot be defined for `geo`.",
);
assert(
containsAny.length +
whereNotIn.length +
whereIn.length +
geoHash.length <=
1,
"Only one of `containsAny`, `where`, `notWhere`, or `geo` may be specified. Duplicate conditions cannot be given.",
);
if (containsAny.isNotEmpty) {
final filter = containsAny.first;
final items = filter.value;
if (items is List && items.isNotEmpty) {
for (final conveter in _converters) {
final res = conveter.collectionQueries(
items,
() => _query(
_createCollection(query),
query,
),
filter,
query,
this,
);
if (res != null) {
return res;
}
}
}
} else if (whereIn.isNotEmpty) {
final filter = whereIn.first;
final items = filter.value;
if (items is List && items.isNotEmpty) {
for (final conveter in _converters) {
final res = conveter.collectionQueries(
items,
() => _query(
_createCollection(query),
query,
),
filter,
query,
this,
);
if (res != null) {
return res;
}
}
}
} else if (whereNotIn.isNotEmpty) {
final filter = whereNotIn.first;
final items = filter.value;
if (items is List && items.isNotEmpty) {
for (final conveter in _converters) {
final res = conveter.collectionQueries(
items,
() => _query(
_createCollection(query),
query,
),
filter,
query,
this,
);
if (res != null) {
return res;
}
}
}
} else if (geoHash.isNotEmpty) {
final filter = geoHash.first;
final items = filter.value;
if (items is List && items.isNotEmpty) {
for (final conveter in _converters) {
final res = conveter.collectionQueries(
items,
() => _query(
_createCollection(query),
query,
),
filter,
query,
this,
);
if (res != null) {
return res;
}
}
}
}
return [
_query(
_createCollection(query),
query,
)
];
}
Query<Map<String, dynamic>> _createCollection(
ModelAdapterCollectionQuery query) {
final path = _path(query.query.path);
if (query.query.filters
.any((e) => e.type == ModelQueryFilterType.collectionGroup)) {
return database.collectionGroup(path.last());
} else {
return database.collection(path);
}
}
ModelUpdateNotificationStatus _status(DocumentChangeType type) {
switch (type) {
case DocumentChangeType.added:
return ModelUpdateNotificationStatus.added;
case DocumentChangeType.modified:
return ModelUpdateNotificationStatus.modified;
case DocumentChangeType.removed:
return ModelUpdateNotificationStatus.removed;
}
}
@override
bool operator ==(Object other) => hashCode == other.hashCode;
@override
int get hashCode {
return prefix.hashCode ^
localDatabase.hashCode ^
options.hashCode ^
database.hashCode ^
initialValue.hashCode;
}
void _assert() {
assert(
prefix.isEmpty ||
!(prefix!.trimQuery().trimString("/").splitLength() <= 0 ||
prefix!.trimQuery().trimString("/").splitLength() % 2 != 0),
"The prefix path hierarchy must be an even number: $prefix",
);
}
}
/// [ModelTransactionRef] for [ListenableFirestoreModelAdapter].
///
/// [ListenableFirestoreModelAdapter]用の[ModelTransactionRef]。
@immutable
class ListenableFirestoreModelTransactionRef extends ModelTransactionRef {
ListenableFirestoreModelTransactionRef._(this._transaction);
final Transaction _transaction;
final List<Future<void> Function()> _localTransaction = [];
}
/// [ModelBatchRef] for [ListenableFirestoreModelAdapter].
///
/// [ListenableFirestoreModelAdapter]用の[ModelBatchRef]。
@immutable
class ListenableFirestoreModelBatchRef extends ModelBatchRef {
ListenableFirestoreModelBatchRef._();
final List<_ListenableFirestoreModelBatchItem> _localBatch = [];
}
@immutable
class _ListenableFirestoreModelBatchItem {
const _ListenableFirestoreModelBatchItem({
required this.path,
this.value,
this.actions,
});
final String path;
final DynamicMap? value;
final Future<void> Function()? actions;
}