findCollectionWithConverter method
Finds a CollectionReference
of type T
based on specified _collectionPath
.
Make sure to have specified the _toJson
and _fromJson
methods or else the FirestoreApi
will not now how to convert the data to T
.
If _tryAddLocalId
is true then your data will also contain a local id field based
on the _idFieldName
specified in the constructor. Add this id field to your T
and you will
have easy access to the document id at any time.
If _tryAddLocalDocumentReference
is true then your data will also contain a local reference field based
on the _documentReferenceFieldName
specified in the constructor. Add this reference field to your T
and you will
have easy access to the document reference at any time.
If you rather want to retrieve data in the raw form of a List<Map<String, dynamic>> consider using the findCollection method instead.
Implementation
Query<T> findCollectionWithConverter() {
_log.info('🔥 Finding ${_collectionPath()} CollectionReference with converter..');
return (_isCollectionGroup
? _firebaseFirestore.collectionGroup(_collectionPath())
: _firebaseFirestore.collection(_collectionPath()))
.withConverter<T>(
fromFirestore: (snapshot, _) {
final data = snapshot.data() ?? {};
try {
return _fromJson!(
data
.tryAddLocalId(
snapshot.id,
idFieldName: _idFieldName,
tryAddLocalId: _tryAddLocalId,
)
.tryAddLocalDocumentReference(
snapshot.reference,
referenceFieldName: _documentReferenceFieldName,
tryAddLocalDocumentReference: _tryAddLocalDocumentReference,
),
);
} catch (error, stackTrace) {
_log.error(
'🔥 Unexpected ${error.runtimeType} caught while serializing ${_collectionPath()} '
'with id: ${snapshot.id} and '
'data: $data',
stackTrace: stackTrace,
error: InvalidJsonException(
id: snapshot.id,
path: snapshot.reference.path,
api: runtimeType.toString(),
data: data,
),
);
_log.info('🔥 Returning error response..');
try {
return _fromJsonError!(
data
.tryAddLocalId(
snapshot.id,
idFieldName: _idFieldName,
tryAddLocalId: _tryAddLocalId,
)
.tryAddLocalDocumentReference(
snapshot.reference,
referenceFieldName: _documentReferenceFieldName,
tryAddLocalDocumentReference: _tryAddLocalDocumentReference,
),
);
} catch (error, stackTrace) {
_log.error(
'🔥 Unexpected ${error.runtimeType} caught while return JSON error ${_collectionPath()} object '
'with id: ${snapshot.id} and '
'data: $data',
error: error,
stackTrace: stackTrace,
);
}
rethrow;
}
},
toFirestore: (data, _) {
try {
return _toJson!(data)
.tryRemoveLocalId(
idFieldName: _idFieldName,
tryRemoveLocalId: _tryAddLocalId,
)
.tryRemoveLocalDocumentReference(
referenceFieldName: _documentReferenceFieldName,
tryRemoveLocalDocumentReference: _tryAddLocalDocumentReference,
);
} catch (error) {
_log.error(
'🔥 Unexpected ${error.runtimeType} caught while deserializing ${_collectionPath()} and '
'data: $data',
);
rethrow;
}
},
);
}