├── .gitignore ├── CHANGELOG.md ├── LICENSE ├── README.md ├── lib ├── src │ ├── timestamp.dart │ └── typed_firestore.dart └── typed_firestore.dart └── pubspec.yaml /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | .dart_tool/ 3 | 4 | .packages 5 | .pub/ 6 | 7 | build/ 8 | 9 | .flutter-plugins 10 | 11 | *.log 12 | 13 | 14 | GeneratedPluginRegistrant.java 15 | Generated.xcconfig 16 | GeneratedPluginRegistrant.h 17 | GeneratedPluginRegistrant.m 18 | .flutter-plugins-dependencies 19 | 20 | *.iml 21 | .idea/ 22 | *.lock 23 | 24 | local.properties 25 | 26 | *.g.dart -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | ## [0.4.4] - 2020-07-17 2 | 3 | - Fixed `==` for `DocSnapshot`. 4 | 5 | 6 | ## [0.4.3] - 2020-07-15 7 | 8 | - Exposed `CollRef.raw` 9 | 10 | 11 | ## [0.4.2] - 2020-01-05 12 | 13 | - Removed duplicate. 14 | 15 | ## [0.4.1] - 2020-01-28 16 | 17 | - Extract `Data` and `DocData` as a separate package (not a file in lib). 18 | 19 | 20 | ## [0.4.0] - 2020-01-28 21 | 22 | - Updated cloud_firestore 23 | - Export `Data` and `DocData` from separate lib to support sharing models with server. 24 | 25 | 26 | ## [0.3.4] - 2019-08-01 27 | 28 | - All types now implements hashCode and `==`. 29 | 30 | ## [0.3.3] - 2019-08-27 31 | 32 | - `.mapList` can now changes type. 33 | 34 | ## [0.3.2] - 2019-08-09 35 | 36 | - Added `DocRef.parent` 37 | 38 | ## [0.3.1] - 2019-08-08 39 | 40 | - Added `collectionGroup` 41 | 42 | 43 | ## [0.3.0] - 2019-08-04 44 | 45 | - `TypedQuery` 46 | - `.getDocs()`: Added `source`. 47 | - `.snapshots()`: Added `includeMetadataChanges`. 48 | 49 | - `DocRef` 50 | - `.get()`: Added `source`. 51 | - `.snapshots()`: Added `includeMetadataChanges`. 52 | 53 | ## [0.2.2] - 2019-07-31 54 | 55 | - `TypedQuery.map` 56 | - `TypedQuery.mapList` 57 | 58 | ## [0.2.1] - 2019-07-31 59 | 60 | - Array-contains query 61 | 62 | ## [0.2.0+1] - 2019-07-10 63 | 64 | - Fixed a bug. 65 | 66 | ## [0.2.0] - 2019-07-10 67 | 68 | - Bumped version of cloud_firestore. 69 | 70 | ## [0.1.1] - 2019-05-16 71 | 72 | startAt, startBefore, endAt, endBefore 73 | 74 | 75 | ## [0.0.3] - 2019-03-24 76 | 77 | Support non-existent docs. 78 | 79 | 80 | ## [0.0.1] - 2018-09-24 81 | 82 | * First release. 83 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | 3 | Version 2.0, January 2004 4 | 5 | http://www.apache.org/licenses/ 6 | 7 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 8 | 9 | 1. Definitions. 10 | 11 | "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. 16 | 17 | "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. 18 | 19 | "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. 20 | 21 | "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. 22 | 23 | "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). 24 | 25 | "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. 26 | 27 | "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." 28 | 29 | "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 30 | 31 | 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 32 | 33 | 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 34 | 35 | 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: 36 | 37 | You must give any other recipients of the Work or Derivative Works a copy of this License; and 38 | You must cause any modified files to carry prominent notices stating that You changed the files; and 39 | You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and 40 | If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. 41 | 42 | You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 43 | 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 44 | 45 | 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 46 | 47 | 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 48 | 49 | 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 50 | 51 | 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. 52 | 53 | END OF TERMS AND CONDITIONS -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # typed_firestore 2 | 3 | Typed firestore entity. 4 | 5 | ## Usage 6 | 7 | 8 | 9 | ```dart 10 | 11 | abstract class Car extends DocData implements Built { 12 | static Serializer get serializer => _$carSerializer; 13 | 14 | String get title; 15 | 16 | @nullable 17 | String get nullableField; 18 | 19 | Car._(); 20 | 21 | factory Car([updates(CarBuilder b)]) = _$Car; 22 | } 23 | 24 | @SerializersFor(const [ 25 | Car, 26 | ]) 27 | Serializers serializers = _$serializers; 28 | 29 | 30 | final firestore = new TypedFirestore( 31 | Firestore.instance, 32 | (serializers.toBuilder()..addPlugin(StandardJsonPlugin())).build(), 33 | ); 34 | 35 | final CollRef cars = firestore.collection('cars'); 36 | 37 | 38 | ``` 39 | -------------------------------------------------------------------------------- /lib/src/timestamp.dart: -------------------------------------------------------------------------------- 1 | import 'package:built_value/serializer.dart'; 2 | import 'package:cloud_firestore/cloud_firestore.dart'; 3 | 4 | class TimestampSerializerPlugin implements SerializerPlugin { 5 | @override 6 | Object? beforeSerialize(Object? object, FullType specifiedType) { 7 | if (object is DateTime && specifiedType.root == DateTime) { 8 | return object.toUtc(); 9 | } 10 | return object; 11 | } 12 | 13 | @override 14 | Object? afterSerialize(Object? object, FullType specifiedType) { 15 | if (specifiedType.root == DateTime) { 16 | return Timestamp.fromMicrosecondsSinceEpoch(object as int); 17 | } 18 | return object; 19 | } 20 | 21 | @override 22 | Object? beforeDeserialize(Object? object, FullType specifiedType) { 23 | if (object is Timestamp && specifiedType.root == DateTime) { 24 | return object.microsecondsSinceEpoch; 25 | // return object.toDate(); 26 | } else { 27 | return object; 28 | } 29 | } 30 | 31 | @override 32 | Object? afterDeserialize(Object? object, FullType specifiedType) { 33 | return object; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /lib/src/typed_firestore.dart: -------------------------------------------------------------------------------- 1 | import 'dart:async'; 2 | 3 | import 'package:built_value/serializer.dart'; 4 | import 'package:built_value/standard_json_plugin.dart'; 5 | import 'package:cloud_firestore/cloud_firestore.dart' as fs; 6 | import 'package:cloud_firestore/cloud_firestore.dart'; 7 | import 'package:quiver/core.dart'; 8 | import 'package:typed_fb_data/data.dart'; 9 | 10 | /// You don't need to add `StandardJsonPlugin`. 11 | class TypedFirestore { 12 | final FirebaseFirestore _inner; 13 | final Serializers _serializers; 14 | 15 | TypedFirestore(this._inner, Serializers serializers) 16 | : _serializers = 17 | (serializers.toBuilder()..addPlugin(StandardJsonPlugin())).build(); 18 | 19 | /// Gets a CollectionReference for the specified Firestore path. 20 | CollRef collection(String path) { 21 | return CollRef._(this, _inner.collection(path)); 22 | } 23 | 24 | /// Gets a Query for the specified collection group. 25 | TypedQuery collectionGroup(String path) { 26 | return TypedQuery(this, _inner.collectionGroup(path)); 27 | } 28 | 29 | /// Gets a DocumentReference for the specified Firestore path. 30 | DocRef doc(String path) { 31 | return DocRef._(this, _inner.doc(path)); 32 | } 33 | 34 | @override 35 | int get hashCode => hash2(_inner, _serializers); 36 | 37 | @override 38 | bool operator ==(other) => 39 | other is TypedFirestore && 40 | this._inner == other._inner && 41 | this._serializers == other._serializers; 42 | } 43 | 44 | /// [DocumentReference] 45 | class DocRef { 46 | const DocRef._(this._firestore, this.raw); 47 | 48 | final TypedFirestore _firestore; 49 | final fs.DocumentReference raw; 50 | 51 | /// This document's given or generated ID in the collection. 52 | String get id => raw.id; 53 | 54 | /// Slash-delimited path representing the database location of this query. 55 | String get path => raw.path; 56 | 57 | /// Parent returns the containing [CollectionReference]. 58 | CollRef parent() => CollRef._(_firestore, raw.parent); 59 | 60 | /// Returns the reference of a collection contained inside of this document. 61 | CollRef collection(String path) => 62 | CollRef._(_firestore, raw.collection(path)); 63 | 64 | /// Returns the reference of a collection contained inside of this document. 65 | Future delete() => raw.delete(); 66 | 67 | /// Reads the document referenced by this DocumentReference 68 | /// 69 | /// If no document exists, the read will return null. 70 | Future> get([GetOptions? options]) async { 71 | return raw.get(options).then( 72 | (ds) => DocSnapshot._fromSnapshot(_firestore, ds), 73 | ); 74 | } 75 | 76 | /// Writes to the document referred to by this DocumentReference. 77 | /// 78 | /// If the document does not yet exist, it will be created. 79 | /// 80 | /// If merge is true, the provided data will be merged into an existing document instead of overwriting. 81 | Future set(D data, [SetOptions? options]) { 82 | return raw.set( 83 | _firestore._serializers.serialize(data, specifiedType: FullType(D)) 84 | as Map, 85 | options, 86 | ); 87 | } 88 | 89 | Stream> snapshots({ 90 | bool includeMetadataChanges = false, 91 | }) { 92 | return raw 93 | .snapshots( 94 | includeMetadataChanges: includeMetadataChanges, 95 | ) 96 | .map((ds) => DocSnapshot._fromSnapshot(_firestore, ds)); 97 | } 98 | 99 | /// Updates fields in the document referred to by this DocumentReference. 100 | /// 101 | /// If no document exists yet, the update will fail. 102 | Future update(D data) { 103 | return raw.update( 104 | _firestore._serializers.serialize(data, specifiedType: FullType(D)) 105 | as Map, 106 | ); 107 | } 108 | 109 | @override 110 | int get hashCode => hash2(_firestore, raw); 111 | 112 | @override 113 | bool operator ==(other) => 114 | other is DocRef && _firestore == other._firestore && raw == other.raw; 115 | } 116 | 117 | /// [DocumentSnapshot] 118 | class DocSnapshot { 119 | DocSnapshot(this.ref, this.data, this.metadata); 120 | 121 | DocSnapshot._from(TypedFirestore firestore, DocRef ref, 122 | Map? data, fs.SnapshotMetadata metadata) 123 | : this( 124 | ref, 125 | data == null 126 | ? null 127 | : firestore._serializers 128 | .deserialize(data, specifiedType: FullType(D)) as D, 129 | metadata, 130 | ); 131 | 132 | /// The reference that produced this snapshot 133 | final DocRef ref; 134 | 135 | DocSnapshot._fromSnapshot(TypedFirestore firestore, fs.DocumentSnapshot ds) 136 | : this._from( 137 | firestore, 138 | DocRef._(firestore, ds.reference), 139 | ds.data(), 140 | ds.metadata, 141 | ); 142 | 143 | /// Contains all the data of this snapshot. 144 | final D? data; 145 | 146 | /// Metadata about a snapshot, describing the state of the snapshot. 147 | final fs.SnapshotMetadata metadata; 148 | 149 | /// Returns the ID of the snapshot's document 150 | String get id => ref.id; 151 | 152 | /// Slash-delimited path representing the database location of this query. 153 | String get path => ref.path; 154 | 155 | /// Returns `true` if the document exists. 156 | bool get exists => data != null; 157 | 158 | @override 159 | int get hashCode => hash2(path, data); 160 | 161 | @override 162 | bool operator ==(other) => 163 | other is DocSnapshot && 164 | this.path == other.path && 165 | this.data == other.data; 166 | } 167 | 168 | /// [QuerySnapshot] 169 | class TypedQuerySnapshot { 170 | final List docChanges; 171 | final List> docs; 172 | final fs.SnapshotMetadata metadata; 173 | 174 | const TypedQuerySnapshot(this.docChanges, this.docs, this.metadata); 175 | 176 | @override 177 | int get hashCode => hash3(docChanges, docs, metadata); 178 | 179 | @override 180 | bool operator ==(other) => 181 | other is TypedQuerySnapshot && 182 | this.docChanges == other.docChanges && 183 | this.docs == other.docs && 184 | this.metadata == other.metadata; 185 | } 186 | 187 | /// [CollectionReference] 188 | class CollRef extends TypedQuery { 189 | final fs.CollectionReference raw; 190 | 191 | const CollRef._(TypedFirestore firestore, this.raw) : super(firestore, raw); 192 | 193 | /// ID of the referenced collection. 194 | String get id => raw.id; 195 | 196 | /// A string containing the slash-separated path to this CollectionReference (relative to the root of the database). 197 | String get path => raw.path; 198 | 199 | /// For subcollections, parent returns the containing [DocumentReference]. 200 | /// 201 | /// For root collections, null is returned. 202 | DocRef

? parent

() { 203 | final p = raw.parent; 204 | if (p == null) return null; 205 | return DocRef._(_firestore, p); 206 | } 207 | 208 | /// Returns a DocumentReference with the provided path. 209 | /// 210 | /// If no path is provided, an auto-generated ID is used. 211 | /// 212 | /// The unique key generated is prefixed with a client-generated timestamp so that the resulting list will be chronologically-sorted. 213 | DocRef doc([String? path]) => DocRef._(_firestore, raw.doc(path)); 214 | 215 | /// Returns a DocumentReference with an auto-generated ID, after populating it with provided data. 216 | /// 217 | /// The unique key generated is prefixed with a client-generated timestamp so that the resulting list will be chronologically-sorted. 218 | Future> add(D data) async { 219 | final DocRef newDocument = doc(); 220 | await newDocument.set(data); 221 | return newDocument; 222 | } 223 | 224 | @override 225 | int get hashCode => hash2(_firestore, raw); 226 | 227 | @override 228 | bool operator ==(other) => 229 | other is CollRef && 230 | this._firestore == other._firestore && 231 | this.raw == other.raw; 232 | } 233 | 234 | class TypedQuery { 235 | final TypedFirestore _firestore; 236 | final fs.Query _inner; 237 | 238 | const TypedQuery(this._firestore, this._inner); 239 | 240 | TypedFirestore get firestore => _firestore; 241 | 242 | /// Creates and returns a new Query with additional filter on specified field. 243 | /// 244 | /// Only documents satisfying provided condition are included in the result set. 245 | TypedQuery where( 246 | String field, { 247 | dynamic isEqualTo, 248 | dynamic isLessThan, 249 | dynamic isLessThanOrEqualTo, 250 | dynamic isGreaterThan, 251 | dynamic isGreaterThanOrEqualTo, 252 | dynamic arrayContains, 253 | bool? isNull, 254 | }) { 255 | return TypedQuery( 256 | _firestore, 257 | _inner.where( 258 | field, 259 | isEqualTo: isEqualTo, 260 | isLessThan: isLessThan, 261 | isLessThanOrEqualTo: isLessThanOrEqualTo, 262 | isGreaterThan: isGreaterThan, 263 | isGreaterThanOrEqualTo: isGreaterThanOrEqualTo, 264 | arrayContains: arrayContains, 265 | isNull: isNull, 266 | )); 267 | } 268 | 269 | /// Takes a list of [values], creates and returns a new [Query] that starts 270 | /// after the provided fields relative to the order of the query. 271 | /// 272 | /// The [values] must be in order of [orderBy] filters. 273 | /// 274 | /// Cannot be used in combination with [startAt], [startAfterDocument], or 275 | /// [startAtDocument]. 276 | TypedQuery startAfter(List values) { 277 | return TypedQuery(_firestore, _inner.startAfter(values)); 278 | } 279 | 280 | /// Takes a list of [values], creates and returns a new [Query] that starts at 281 | /// the provided fields relative to the order of the query. 282 | /// 283 | /// The [values] must be in order of [orderBy] filters. 284 | /// 285 | /// Cannot be used in combination with [startAfter], [startAfterDocument], 286 | /// or [startAtDocument]. 287 | TypedQuery startAt(List values) { 288 | return TypedQuery(_firestore, _inner.startAt(values)); 289 | } 290 | 291 | // TODO: TypedQuery endAtDocument 292 | 293 | /// Takes a list of [values], creates and returns a new [Query] that ends at the 294 | /// provided fields relative to the order of the query. 295 | /// 296 | /// The [values] must be in order of [orderBy] filters. 297 | /// 298 | /// Cannot be used in combination with [endBefore], [endBeforeDocument], or 299 | /// [endAtDocument]. 300 | TypedQuery endAt(List values) { 301 | return TypedQuery(_firestore, _inner.endAt(values)); 302 | } 303 | 304 | /// Takes a list of [values], creates and returns a new [Query] that ends before 305 | /// the provided fields relative to the order of the query. 306 | /// 307 | /// The [values] must be in order of [orderBy] filters. 308 | /// 309 | /// Cannot be used in combination with [endAt], [endBeforeDocument], or 310 | /// [endBeforeDocument] 311 | TypedQuery endBefore(List values) { 312 | return TypedQuery(_firestore, _inner.endBefore(values)); 313 | } 314 | 315 | /// Creates and returns a new Query that's additionally limited to only return up to the specified number of documents. 316 | TypedQuery limit(int length) => 317 | TypedQuery(_firestore, _inner.limit(length)); 318 | 319 | /// Creates and returns a new Query that's additionally sorted by the specified field. 320 | TypedQuery orderBy( 321 | String field, { 322 | bool descending: false, 323 | }) => 324 | TypedQuery( 325 | _firestore, 326 | _inner.orderBy( 327 | field, 328 | descending: descending, 329 | )); 330 | 331 | /// `mapper` is called **after** fetching documents. 332 | TypedQuery mapList( 333 | Mapper>, List>> mapper) { 334 | return _MapList( 335 | firestore: _firestore, 336 | inner: _inner, 337 | mapper: mapper, 338 | ); 339 | } 340 | 341 | /// `mapper` is called **after** fetching documents. 342 | TypedQuery map(Mapper mapper) { 343 | return _MappedQuery( 344 | firestore: _firestore, 345 | inner: _inner, 346 | mapper: (v) { 347 | if (v == null) return null; 348 | return mapper(v); 349 | }, 350 | ); 351 | } 352 | 353 | /// Fetch the documents for this query 354 | /// 355 | Future> getDocs([GetOptions? options]) async { 356 | final qs = await _inner.get(options); 357 | 358 | return TypedQuerySnapshot( 359 | qs.docChanges, 360 | qs.docs 361 | .map((ds) => DocSnapshot._fromSnapshot(_firestore, ds)) 362 | .toList(growable: false), 363 | qs.metadata, 364 | ); 365 | } 366 | 367 | /// Notifies of query results at this location 368 | Stream> snapshots({ 369 | bool includeMetadataChanges = false, 370 | }) { 371 | return _inner 372 | .snapshots( 373 | includeMetadataChanges: includeMetadataChanges, 374 | ) 375 | .map((qs) { 376 | return TypedQuerySnapshot( 377 | qs.docChanges, 378 | qs.docs 379 | .map((ds) => DocSnapshot._fromSnapshot(_firestore, ds)) 380 | .toList(growable: false), 381 | qs.metadata, 382 | ); 383 | }); 384 | } 385 | 386 | @override 387 | int get hashCode => hash2(_inner, _firestore); 388 | 389 | @override 390 | bool operator ==(other) => 391 | other is TypedQuery && 392 | this._inner == other._inner && 393 | this._firestore == other._firestore; 394 | } 395 | 396 | /// Mapper maps `S` into `T`. 397 | typedef FutureOr Mapper(S data); 398 | 399 | class _MappedQuery extends TypedQuery { 400 | final Mapper mapper; 401 | 402 | _MappedQuery({ 403 | required TypedFirestore firestore, 404 | required fs.Query inner, 405 | required this.mapper, 406 | }) : super(firestore, inner); 407 | 408 | /// Fetch the documents for this query 409 | /// 410 | Future> getDocs([GetOptions? options]) async { 411 | final qs = await _inner.get(options); 412 | 413 | final docs = await Future.wait( 414 | qs.docs.map((fs.DocumentSnapshot ds) async { 415 | final ss = DocSnapshot._fromSnapshot(_firestore, ds); 416 | return DocSnapshot(ss.ref, await mapper(ss.data), ss.metadata); 417 | }).toList(growable: false), 418 | ); 419 | 420 | return TypedQuerySnapshot( 421 | qs.docChanges, 422 | docs, 423 | qs.metadata, 424 | ); 425 | } 426 | 427 | /// Notifies of query results at this location 428 | Stream> snapshots({ 429 | bool includeMetadataChanges = false, 430 | }) async* { 431 | await for (final qs in _inner.snapshots( 432 | includeMetadataChanges: includeMetadataChanges, 433 | )) { 434 | final docs = await Future.wait( 435 | qs.docs.map((ds) async { 436 | final ss = DocSnapshot._fromSnapshot(_firestore, ds); 437 | return DocSnapshot(ss.ref, await mapper(ss.data), ds.metadata); 438 | }).toList(growable: false), 439 | ); 440 | 441 | yield TypedQuerySnapshot( 442 | qs.docChanges, 443 | docs, 444 | qs.metadata, 445 | ); 446 | } 447 | } 448 | 449 | @override 450 | int get hashCode => hash3(_inner, _firestore, mapper); 451 | 452 | @override 453 | bool operator ==(other) => 454 | other is _MappedQuery && 455 | this._inner == other._inner && 456 | this._firestore == other._firestore && 457 | this.mapper == other.mapper; 458 | } 459 | 460 | class _MapList extends TypedQuery { 461 | final Mapper>, List>> mapper; 462 | 463 | _MapList({ 464 | required TypedFirestore firestore, 465 | required fs.Query inner, 466 | required this.mapper, 467 | }) : super(firestore, inner); 468 | 469 | /// Fetch the documents for this query 470 | /// 471 | Future> get([GetOptions? options]) async { 472 | final qs = await _inner.get(options); 473 | 474 | return TypedQuerySnapshot( 475 | qs.docChanges, 476 | await mapper( 477 | qs.docs.map((ds) { 478 | return DocSnapshot._fromSnapshot(_firestore, ds); 479 | }).toList(growable: false), 480 | ), 481 | qs.metadata, 482 | ); 483 | } 484 | 485 | /// Notifies of query results at this location 486 | Stream> snapshots({ 487 | bool includeMetadataChanges = false, 488 | }) async* { 489 | await for (final qs in _inner.snapshots( 490 | includeMetadataChanges: includeMetadataChanges, 491 | )) { 492 | yield TypedQuerySnapshot( 493 | qs.docChanges, 494 | await mapper( 495 | qs.docs.map((ds) { 496 | return DocSnapshot._fromSnapshot(_firestore, ds); 497 | }).toList( 498 | growable: false, 499 | ), 500 | ), 501 | qs.metadata, 502 | ); 503 | } 504 | } 505 | 506 | @override 507 | int get hashCode => hash3(_inner, _firestore, mapper); 508 | @override 509 | bool operator ==(other) => 510 | other is _MapList && 511 | this._inner == other._inner && 512 | this._firestore == other._firestore && 513 | this.mapper == other.mapper; 514 | } 515 | -------------------------------------------------------------------------------- /lib/typed_firestore.dart: -------------------------------------------------------------------------------- 1 | library typed_firestore; 2 | 3 | export 'package:typed_fb_data/data.dart'; 4 | 5 | export 'src/typed_firestore.dart'; 6 | -------------------------------------------------------------------------------- /pubspec.yaml: -------------------------------------------------------------------------------- 1 | name: typed_firestore 2 | description: Typed firebase.storage for flutter 3 | homepage: https://github.com/kdy1/typed_firestore 4 | version: 0.6.0 5 | 6 | environment: 7 | sdk: ">=2.12.0 <3.0.0" 8 | 9 | dependencies: 10 | flutter: 11 | sdk: flutter 12 | built_value: ^8.0.2 13 | cloud_firestore: ^1.0.1 14 | quiver: '^3.0.0' 15 | typed_fb_data: ^0.2.1 16 | 17 | dev_dependencies: 18 | flutter_test: 19 | sdk: flutter 20 | 21 | --------------------------------------------------------------------------------