getByIdWithConverter method

Future<TurboResponse<T>> getByIdWithConverter({
  1. required String id,
  2. String? collectionPathOverride,
})

Retrieves and converts a document by its unique identifier

Returns document data converted to type T using _fromJson Provides type-safe access to Firestore data

Parameters: id unique identifier of the document collectionPathOverride override path for collection groups

Returns TurboResponse containing:

  • Success with typed document data
  • Empty fail when document not found
  • Fail with error details on operation failure

Features:

  • Automatic type conversion
  • Local ID field management
  • Document reference handling
  • Type-safe error handling
  • Error logging

Example:

final response = await api.getByIdWithConverter(id: 'user-123');
response.when(
  success: (user) => print('Found user ${user.name}'),
  fail: (error) => print('Error $error'),
);

See also:

Implementation

Future<TurboResponse<T>> getByIdWithConverter({
  required String id,
  String? collectionPathOverride,
}) async {
  assert(
    _isCollectionGroup == (collectionPathOverride != null),
    'Firestore does not support finding a document by id when communicating with a collection group, '
    'therefore, you must specify the collectionPathOverride containing all parent collection and document ids '
    'in order to make this method work.',
  );
  try {
    _log.debug(
      message: 'Finding with converter..',
      sensitiveData: SensitiveData(
        path: collectionPathOverride ?? _collectionPath(),
        id: id,
      ),
    );
    final result = (await getDocRefByIdWithConverter(
      id: id,
      collectionPathOverride: collectionPathOverride,
    ).get(_getOptions))
        .data();
    if (result != null) {
      _log.info(
        message: 'Found item!',
        sensitiveData: null,
      );
      return TurboResponse.success(result: result);
    } else {
      _log.warning(
        message: 'Found nothing!',
        sensitiveData: null,
      );
      return TurboResponse.fail(
          error: 'Document not found',
          title: 'Not Found',
          message: 'The requested document was not found');
    }
  } catch (error, stackTrace) {
    _log.error(
      message: 'Unable to find document',
      error: error,
      stackTrace: stackTrace,
      sensitiveData: SensitiveData(
        path: collectionPathOverride ?? _collectionPath(),
        id: id,
      ),
    );

    // Convert to TurboFirestoreException and wrap in TurboResponse
    final exception = TurboFirestoreException.fromFirestoreException(
      error,
      stackTrace,
      path: collectionPathOverride ?? _collectionPath(),
      query: 'getByIdWithConverter(id: $id)',
    );

    return TurboResponse.fail(error: exception);
  }
}