request<T> method

  1. @override
Future<T> request<T>(
  1. Endpoint endpoint, {
  2. Map<String, dynamic>? queryParams,
  3. Map<String, String>? pathParams,
  4. dynamic body,
})
override

Executes a request for a given endpoint.

Implementation

@override
Future<T> request<T>(
  Endpoint endpoint, {
  Map<String, dynamic>? queryParams,
  Map<String, String>? pathParams,
  dynamic body,
}) async {
  final path = endpoint.buildPath(pathParams);

  if (endpoint.requiresAuth && _auth.currentUser == null) {
    throw Exception('Authentication required for endpoint: ${endpoint.id}');
  }

  // Handle Storage requests
  if (path.startsWith('storage://')) {
    return _handleStorageRequest<T>(endpoint, path, body);
  }

  try {
    final pathSegments = path.split('/').where((s) => s.isNotEmpty).toList();

    if (pathSegments.length % 2 == 0) {
      // Document path
      final docRef = _firestore.doc(path);

      if (body != null) {
        final enrichedBody = _enrichData(body);
        await docRef.set(enrichedBody, SetOptions(merge: true));
        return enrichedBody as T;
      } else {
        final snapshot = await docRef.get();
        final data = snapshot.data();
        if (data == null) throw Exception('Document not found at $path');

        final enrichedData = _attachMetadata(data, snapshot.id);
        return endpoint.parser != null
            ? endpoint.parser!(enrichedData) as T
            : enrichedData as T;
      }
    } else {
      // Collection path
      final colRef = _firestore.collection(path);

      if (body != null) {
        final enrichedBody = _enrichData(body);
        final doc = await colRef.add(enrichedBody);
        final data = {...enrichedBody, 'id': doc.id};
        return data as T;
      } else {
        final query = _applyQueries(colRef, queryParams);
        final snapshot = await query.get();
        final list = snapshot.docs
            .map((d) =>
                _attachMetadata(d.data() as Map<String, dynamic>, d.id))
            .toList();

        return endpoint.parser != null
            ? endpoint.parser!(list) as T
            : list as T;
      }
    }
  } catch (e) {
    rethrow;
  }
}